package com.xoa.service.document.Impl;

import com.alibaba.fastjson.JSONArray;
import com.xoa.controller.AI.AIController;
import com.xoa.dao.WFE.WFEFlowRunMapper;
import com.xoa.dao.WFE.WFEFlowRunPrcsMapper;
import com.xoa.dao.WFE.WFEFlowTypeModelMapper;
import com.xoa.dao.WFE.WFEFormTypeMapper;
import com.xoa.dao.common.SysCodeMapper;
import com.xoa.dao.document.DocumentModelMapper;
import com.xoa.dao.document.SysRuleModelMapper;
import com.xoa.dao.documentOrg.DocumentOrgMapper;
import com.xoa.dao.enclosure.AttachmentMapper;
import com.xoa.dao.modulePriv.ModulePrivMapper;
import com.xoa.dao.template.TemplateModuleMapper;
import com.xoa.dao.users.UsersMapper;
import com.xoa.dao.work.WorkMapper;
import com.xoa.dao.workflow.FlowAssignMapper;
import com.xoa.dao.workflow.FlowProcessMapper;
import com.xoa.dao.workflow.FlowRunPrcsMapper;
import com.xoa.dao.workflow.ToBeReadMapper;
import com.xoa.dev.efficiency.dao.FlowAbilityMonitorMapper;
import com.xoa.model.common.SysCode;
import com.xoa.model.department.Department;
import com.xoa.model.document.*;
import com.xoa.model.documentOrg.DocumentOrg;
import com.xoa.model.documentOrg.DocumentOrgWithBLOBs;
import com.xoa.model.enclosure.Attachment;
import com.xoa.model.sms.SmsBody;
import com.xoa.model.sys.SealWithBLOBs;
import com.xoa.model.template.TemplateModule;
import com.xoa.model.users.UserPriv;
import com.xoa.model.users.Users;
import com.xoa.model.workflow.*;
import com.xoa.service.WFE.WFEFactory.WFEFlowType;
import com.xoa.service.WFE.WFERunner.WFEFlowRun;
import com.xoa.service.WFE.WFERunner.WFEFlowRunInfo;
import com.xoa.service.WFE.WFERunner.WFEFlowRunPrcs;
import com.xoa.service.document.DocumentSerivce;
import com.xoa.service.documentOrg.DocumentOrgService;
import com.xoa.service.enclosure.EnclosureService;
import com.xoa.service.sms.SmsService;
import com.xoa.service.sys.SealService;
import com.xoa.service.users.UsersService;
import com.xoa.service.work.WorkService;
import com.xoa.service.work.impl.WorkServiceImpl;
import com.xoa.service.workflow.toBeRead.ToBeReadService;
import com.xoa.util.*;
import com.xoa.util.common.StringUtils;
import com.xoa.util.common.constants.DocumentConstants;
import com.xoa.util.common.session.SessionUtils;
import com.xoa.util.common.wrapper.BaseWrappers;
import com.xoa.util.dataSource.ContextHolder;
import com.xoa.util.page.PageParams;
import org.apache.ibatis.annotations.Param;
import org.jsoup.nodes.Document;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;
import sun.misc.BASE64Encoder;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Service
public class DocumentSerivceImpl implements DocumentSerivce {
    @Resource
    DocumentModelMapper documentModelMapper;
    @Resource
    SysRuleModelMapper sysRuleModelMapper;
    @Resource
    FlowRunPrcsMapper flowRunPrcsMapper;
    @Resource
    WorkService workService;
    @Resource
    FlowProcessMapper flowProcessMapper;
    @Resource
    UsersService usersService;
    @Autowired
    SmsService smsService;
    @Resource
    private SealService sealService;
    @Resource
    UsersMapper usersMapper;
    @Resource
    private WFEFlowRunInfo wfeFlowRunInfo;

    @Resource
    private ToBeReadMapper toBeReadMapper;

    @Autowired
    private TemplateModuleMapper templateModuleMapper;


    @Autowired
    private WFEFlowRunPrcsMapper wfeFlowRunPrcsMapper;

    @Autowired
    private WFEFlowRunMapper wfeFlowRunMapper;

    @Autowired
    private WFEFlowRunPrcs wfeFlowRunPrcs;

    @Autowired
    DocumentOrgService documentOrgService;

    @Autowired
    DocumentOrgMapper documentOrgMapper;
    @Autowired
    SysCodeMapper sysCodeMapper;
    @Autowired
    WFEFormTypeMapper wfeFormTypeMapper;
    @Autowired
    WorkMapper workMapper;
    @Resource
    private ModulePrivMapper modulePrivMapper;

    @Resource
    private FlowAssignMapper flowAssignMapper;
    @Resource
    private EnclosureService enclosureService;
    @Resource
    private AIController aiController;

    @Autowired
    WFEFlowRun wfeFlowRun;
    @Resource
    ThreadPoolTaskExecutor threadPoolTaskExecutor;

    @Autowired
    private AttachmentMapper attachmentMapper;


    public int saveSysRule(SysRuleModel sysRule) {
        return sysRuleModelMapper.saveSysRule(sysRule);
    }

    public int deleteSysRule(SysRuleModel sysRule) {
        return sysRuleModelMapper.deleteSysRule(sysRule);
    }

    public int updateRuleById(SysRuleModel sysRule) {
        return sysRuleModelMapper.updateRuleById(sysRule);
    }

    public int updateRunIdById(SysRuleModel sysRuleModel) {
        return sysRuleModelMapper.updateRunIdById(sysRuleModel);
    }

    public SysRuleModel getRuleById(SysRuleModel sysRule,
                                    HttpServletRequest request) {
        SysRuleModel sys = sysRuleModelMapper.getRuleById(sysRule);
        String expression = sys.getExpression();
        String transforedExpression = this.transfor(expression, request, sys);
        List<String> titleList = new ArrayList<String>();
        List<String> expressionList = new ArrayList<String>();
        sys.setExpressionStr(expression);
        String expressionStr = sys.getExpressionStr();
        // 定义正则表达式
        Pattern pattern = Pattern.compile("(?<=\\[)(.+?)(?=\\])");
        Matcher matcher = pattern.matcher(expression);
        Calendar now = Calendar.getInstance();
        // 匹配规则字段
        String str = null;

        while (matcher.find()) {
            switch (matcher.group()) {
                // 短年份
                case SHOT_YEAR:
                    str = String.valueOf(now.get(Calendar.YEAR));
                    titleList.add("短年份");
                    expressionList.add(str.substring(str.length() - 2));
                    expressionStr = expressionStr.replace("[YY]",
                            " " + str.substring(str.length() - 2) + " ");
                    break;
                // 年份
                case All_YEAR:
                    str = String.valueOf(now.get(Calendar.YEAR));
                    titleList.add("全年份");
                    expressionList.add(str);
                    expressionStr = expressionStr.replace("[ALL_YY]", " " + str
                            + " ");
                    break;
                // 日期
                case DATE:
                    str = (new SimpleDateFormat("yyyy-MM-dd"))
                            .format(new Date());
                    titleList.add("日期");
                    expressionList.add(str);
                    expressionStr = expressionStr.replace("[DATE]", " " + str
                            + " ");
                    break;
                // 日期带时分秒
                case DATE_TIME:
                    str = (new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"))
                            .format(new Date());
                    titleList.add("日期时间");
                    expressionList.add(str);
                    expressionStr = expressionStr.replace("[DATE_TIME]", " "
                            + str + " ");
                    break;
                // 01 02 日
                case H_MOS:
                    int day = now.get(Calendar.DAY_OF_MONTH);
                    if (day < 10) {
                        str = "0" + day;
                    } else {
                        str = String.valueOf(day);
                    }
                    titleList.add("长日期");
                    expressionList.add(str);
                    expressionStr = expressionStr.replace("[H_MOS]", " " + str
                            + " ");
                    break;
                // 1 2 日
                case H_MO:
                    str = String.valueOf(now.get(Calendar.DAY_OF_MONTH));
                    titleList.add("短日期");
                    expressionList.add(str);
                    expressionStr = expressionStr.replace("[H_MO]", " " + str
                            + " ");
                    break;
                // 01 02 月份
                case MONTHS:
                    int month = now.get(Calendar.MONTH) + 1;
                    if (month < 10) {
                        str = "0" + month;
                    } else {
                        str = String.valueOf(month);
                    }
                    titleList.add("长月份");
                    expressionList.add(str);
                    expressionStr = expressionStr.replace("[MONTHS]", " " + str
                            + " ");
                    break;
                // 1 2 月份
                case MONTH:
                    str = String.valueOf(now.get(Calendar.MONTH) + 1);
                    titleList.add("短月份");
                    expressionList.add(str);
                    expressionStr = expressionStr.replace("[MONTH]", " " + str
                            + " ");
                    break;
                // 获取计数器
                case COUNTER:
                    int number = sys.getCounter();
                    String str1 = String.format("%0" + sys.getDigit() + "d", number);
                    str = String.valueOf(sys.getCounter());
                    expressionStr = expressionStr.replace("[COUNTER]", " "
                            + str1 + " ");
                    break;

            }
        }
        // 获取计数器
        str = String.valueOf(sys.getCounter());
        titleList.add("计数器");
        expressionList.add(str);
        sys.setExpressionStr(expressionStr);
        sys.setRuleTitles(titleList);
        sys.setRuleExps(expressionList);
        return sys;
    }

    private String transfor(String expression, HttpServletRequest request,
                            SysRuleModel sys) {
        String date2 = DateFormat.getCurrentTime();
        Date date = DateFormat.getDate(date2);
        Calendar c = Calendar.getInstance();
        int datenum = c.get(Calendar.DATE);
        String userName = String.valueOf(request.getSession().getAttribute(
                "userName"));
        @SuppressWarnings("deprecation")
        String expression2 = expression
                .replace(DocumentConstants.year,
                        String.valueOf(date.getYear() + 1900))
                .replace(
                        DocumentConstants.month,
                        String.valueOf((date.getMonth() + 1) < 10 ? "0"
                                + (date.getMonth() + 1) : date.getMonth() + 1))
                .replace(DocumentConstants.day, String.valueOf(datenum))
                .replace(DocumentConstants.hour,
                        String.valueOf(date.getHours()))
                .replace(DocumentConstants.minute,
                        String.valueOf(date.getMinutes()))
                .replace(DocumentConstants.second,
                        String.valueOf(date.getSeconds()))
                .replace(DocumentConstants.user, userName)
                .replace(DocumentConstants.flow, "流程名")
                .replace(DocumentConstants.flowName, "流程分类名称 公文")
                .replace(DocumentConstants.longDept, "长部门名")
                .replace(DocumentConstants.shortDept, "短部门名")
                .replace(DocumentConstants.runId, "流水号")
                .replace(DocumentConstants.number, "编号")
                .replace(DocumentConstants.numberMonth, "重新按月编号")
                .replace(DocumentConstants.numberYear, "重新编号按年");
        return expression2;
    }

    public List<SysRuleModel> getRuleAll(SysRuleModel sysRule,HttpServletRequest request) {
        Cookie redisSessionCookie = CookiesUtil.getCookieByName(request, "redisSessionId");
        Users sessionUser = SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users(),redisSessionCookie);
        List<SysRuleModel> ruleAll = sysRuleModelMapper.getRuleAll(sysRule);
        for (SysRuleModel t : ruleAll) {
            // 用户
            if (!StringUtils.checkNull(t.getPrivUser())) {
                String[] split = t.getPrivUser().split(",");
                List<Users> usersByUids = usersMapper.getUsersByUserIds(split);
                if (usersByUids != null && usersByUids.size() > 0) {
                    StringBuffer sb = new StringBuffer();
                    for (Users u : usersByUids) {
                        sb.append(u.getUserName() + ",");
                    }
                    t.setPrivUserString(t.getPrivUser());
                    t.setPrivUser(sb.toString());
                }
            } else {
                t.setPrivUser("");
                t.setPrivUserString("");
            }

            // 部门
            if (!StringUtils.checkNull(t.getPrivDept())) {
                String[] split = t.getPrivDept().split(",");
                List<Department> deptNameByIds = modulePrivMapper.getDeptNameByIds(split);
                if (deptNameByIds != null && deptNameByIds.size() > 0) {
                    StringBuffer sb = new StringBuffer();
                    for (Department d : deptNameByIds) {
                        sb.append(d.getDeptName() + ",");
                    }
                    t.setPrivDeptString(t.getPrivDept());
                    t.setPrivDept(sb.toString());
                }
            } else {
                t.setPrivDept("");
                t.setPrivDeptString("");
            }

            // 角色
            if (!StringUtils.checkNull(t.getPrivRole())) {
                String[] split = t.getPrivRole().split(",");
                List<UserPriv> privNameByIds = modulePrivMapper.getPrivNameByIds(split);
                if (privNameByIds != null && privNameByIds.size() > 0) {
                    StringBuffer sb = new StringBuffer();
                    for (UserPriv up : privNameByIds) {
                        sb.append(up.getPrivName() + ",");
                    }
                    t.setPrivRoleString(t.getPrivRole());
                    t.setPrivRole(sb.toString());
                }
            } else {
                t.setPrivRole("");
                t.setPrivRoleString("");
            }
        }

        for (SysRuleModel s : ruleAll) {
            String expression = s.getExpression();
            s.setExpressionStr(expression);
            String expressionStr = s.getExpressionStr();
            // 定义正则表达式
            Pattern pattern = Pattern.compile("(?<=\\[)(.+?)(?=\\])");
            Matcher matcher = pattern.matcher(expression);
            Calendar now = Calendar.getInstance();
            // 匹配规则字段
            String str = null;

            while (matcher.find()) {
                switch (matcher.group()) {
                    // 短年份
                    case SHOT_YEAR:
                        str = String.valueOf(now.get(Calendar.YEAR));
                        expressionStr = expressionStr.replace("[YY]",
                                " " + str.substring(str.length() - 2) + " ");
                        break;
                    // 年份
                    case All_YEAR:
                        str = String.valueOf(now.get(Calendar.YEAR));
                        expressionStr = expressionStr.replace("[ALL_YY]", " " + str
                                + " ");
                        break;
                    // 日期
                    case DATE:
                        str = (new SimpleDateFormat("yyyy-MM-dd"))
                                .format(new Date());
                        expressionStr = expressionStr.replace("[DATE]", " " + str
                                + " ");
                        break;
                    // 日期带时分秒
                    case DATE_TIME:
                        str = (new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"))
                                .format(new Date());
                        expressionStr = expressionStr.replace("[DATE_TIME]", " "
                                + str + " ");
                        break;
                    // 01 02 日
                    case H_MOS:
                        int day = now.get(Calendar.DAY_OF_MONTH);
                        if (day < 10) {
                            str = "0" + day;
                        } else {
                            str = String.valueOf(day);
                        }
                        expressionStr = expressionStr.replace("[H_MOS]", " " + str
                                + " ");
                        break;
                    // 1 2 日
                    case H_MO:
                        str = String.valueOf(now.get(Calendar.DAY_OF_MONTH));
                        expressionStr = expressionStr.replace("[H_MO]", " " + str
                                + " ");
                        break;
                    // 01 02 月份
                    case MONTHS:
                        int month = now.get(Calendar.MONTH) + 1;
                        if (month < 10) {
                            str = "0" + month;
                        } else {
                            str = String.valueOf(month);
                        }
                        expressionStr = expressionStr.replace("[MONTHS]", " " + str
                                + " ");
                        break;
                    // 1 2 月份
                    case MONTH:
                        str = String.valueOf(now.get(Calendar.MONTH) + 1);
                        expressionStr = expressionStr.replace("[MONTH]", " " + str
                                + " ");
                        break;
                    // 获取计数器
                    case COUNTER:
                        int number = s.getCounter();
                        String str1 = String.format("%0" + s.getDigit() + "d", number);
                        str = String.valueOf(s.getCounter());
                        expressionStr = expressionStr.replace("[COUNTER]", " "
                                + str1 + " ");
                        break;
                }
            }
            // 重新赋值
            s.setExpressionStr(expressionStr);
        }
        return ruleAll;
    }

    public List<SysRuleModel> getRuleAll2(SysRuleModel sysRule,HttpServletRequest request) {
        Cookie redisSessionCookie = CookiesUtil.getCookieByName(request, "redisSessionId");
        Users sessionUser = SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users(),redisSessionCookie);
        List<SysRuleModel> ruleAll = sysRuleModelMapper.getRuleAll(sysRule);
        List<SysRuleModel> end = new ArrayList<SysRuleModel>();

        for (SysRuleModel list1:ruleAll) {//判断权限
            if (!StringUtils.checkNull(list1.getPrivUser())) {
                String[] split1 = list1.getPrivUser().split(",");
                for (String list2 : split1) {
                    if (sessionUser.getUserId().equals(list2)) {
                        end.add(list1);
                    }
                }
            } else if (!StringUtils.checkNull(list1.getPrivDept())) {
                String[] split2 = list1.getPrivDept().split(",");
                for (String list3 : split2) {
                    if (sessionUser.getUserId().equals(list3)) {
                        end.add(list1);
                    }
                }
            } else if (!StringUtils.checkNull(list1.getPrivRole())) {
                String[] split3 = list1.getPrivRole().split(",");
                for (String list4 : split3) {
                    if ((sessionUser.getUserPriv()+"").equals(list4)) {
                        end.add(list1);
                    }
                }
            }
        }




        for (SysRuleModel s : end) {
            String expression = s.getExpression();
            s.setExpressionStr(expression);
            String expressionStr = s.getExpressionStr();
            // 定义正则表达式
            Pattern pattern = Pattern.compile("(?<=\\[)(.+?)(?=\\])");
            Matcher matcher = pattern.matcher(expression);
            Calendar now = Calendar.getInstance();
            // 匹配规则字段
            String str = null;

            while (matcher.find()) {
                switch (matcher.group()) {
                    // 短年份
                    case SHOT_YEAR:
                        str = String.valueOf(now.get(Calendar.YEAR));
                        expressionStr = expressionStr.replace("[YY]",
                                " " + str.substring(str.length() - 2) + " ");
                        break;
                    // 年份
                    case All_YEAR:
                        str = String.valueOf(now.get(Calendar.YEAR));
                        expressionStr = expressionStr.replace("[ALL_YY]", " " + str
                                + " ");
                        break;
                    // 日期
                    case DATE:
                        str = (new SimpleDateFormat("yyyy-MM-dd"))
                                .format(new Date());
                        expressionStr = expressionStr.replace("[DATE]", " " + str
                                + " ");
                        break;
                    // 日期带时分秒
                    case DATE_TIME:
                        str = (new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"))
                                .format(new Date());
                        expressionStr = expressionStr.replace("[DATE_TIME]", " "
                                + str + " ");
                        break;
                    // 01 02 日
                    case H_MOS:
                        int day = now.get(Calendar.DAY_OF_MONTH);
                        if (day < 10) {
                            str = "0" + day;
                        } else {
                            str = String.valueOf(day);
                        }
                        expressionStr = expressionStr.replace("[H_MOS]", " " + str
                                + " ");
                        break;
                    // 1 2 日
                    case H_MO:
                        str = String.valueOf(now.get(Calendar.DAY_OF_MONTH));
                        expressionStr = expressionStr.replace("[H_MO]", " " + str
                                + " ");
                        break;
                    // 01 02 月份
                    case MONTHS:
                        int month = now.get(Calendar.MONTH) + 1;
                        if (month < 10) {
                            str = "0" + month;
                        } else {
                            str = String.valueOf(month);
                        }
                        expressionStr = expressionStr.replace("[MONTHS]", " " + str
                                + " ");
                        break;
                    // 1 2 月份
                    case MONTH:
                        str = String.valueOf(now.get(Calendar.MONTH) + 1);
                        expressionStr = expressionStr.replace("[MONTH]", " " + str
                                + " ");
                        break;
                    // 获取计数器
                    case COUNTER:
                        int number = s.getCounter();
                        String str1 = String.format("%0" + s.getDigit() + "d", number);
                        str = String.valueOf(s.getCounter());
                        expressionStr = expressionStr.replace("[COUNTER]", " "
                                + str1 + " ");
                        break;
                }
            }
            // 重新赋值
            s.setExpressionStr(expressionStr);
        }
        return end;
    }

    @Override
    public SysRuleModel getRuleByCode(SysRuleModel sysRule) {
        return sysRuleModelMapper.getRuleByCode(sysRule);
    }

    @Override
    public ToJson<Object> saveDocument(Users user, Integer fflowId, Integer fflowStep, String fprcsId, String frunName, DocumentModelWithBLOBs document, HttpServletRequest request
    ) {
        ToJson<Object> toJson = new ToJson<Object>();
        try {
            String cureTime = DateFormat.getCurrentTime2();
            document.setPrintDate(cureTime);

            String sqlType = "xoa" + (String) request.getSession().getAttribute(
                    "loginDateSouse"); //当前库

            ToJson<FlowFast> flowFastToJson = wfeFlowRunInfo.workFastAdd(user, fflowId, fflowStep, fprcsId, "", request, sqlType, frunName, null);

            if (flowFastToJson.isFlag()) {
                FlowFast fast = (FlowFast) flowFastToJson.getObject();
                Integer runId = fast.getFlowRun().getRunId(); //xin
                Integer flowId = fast.getFlowRun().getFlowId();


                if (document.getRunId() != null) {
                    //切回发公文的库
                    String firstDBSource = "xoa" + document.getTransferOrg();
                    // 数据库切换
                    ContextHolder.setConsumerType(firstDBSource);
                    Map map = new HashMap();
                    map.put("runId", document.getRunId());
                    //修改附件
                    FlowRun flowRun = wfeFlowRunMapper.find(map);

                    if (flowRun != null) {
                        //复制流程附件
                        documentOrgService.copyWordAndAIPFile(flowRun, null, firstDBSource, sqlType);
                        map.clear(); //清空
                        map.put("attachmentId", flowRun.getAttachmentId());
                        map.put("attachmentName", flowRun.getAttachmentName());
                        map.put("runId", runId);

                        //切回当前库
                        ContextHolder.setConsumerType(sqlType);
                        wfeFlowRunMapper.updateAttachment(map);

                        DocumentOrgWithBLOBs documentOrgWithBLOBs = new DocumentOrgWithBLOBs();
                        documentOrgWithBLOBs.setId(document.getId());
                        documentOrgWithBLOBs.setRunId(runId);
                        documentOrgWithBLOBs.setFlowId(flowId);
                        documentOrgMapper.updateByPrimaryKeySelective(documentOrgWithBLOBs);
                    }
                }


                document.setRunId(runId); //新
                document.setFlowId(flowId);
                Date date = new Date();
                document.setTitle(StringUtils.checkNull(document.getTitle()) ? fast.getFlowRun().getRunName() : document.getTitle());
                //SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                //String time = sdf.format(date);
                document.setcTime(date);
               /* Integer check = documentModelMapper.checkRunId(runId);
                if (check!=null&&1==check){
                    toJson.setMsg("重号，请重试！");
                    toJson.setFlag(1);
                    return toJson;
                }*/
                int result = documentModelMapper.insertSelective(document);
                DocumentModelWithBLOBs newDoc = documentModelMapper.selectByPrimaryKey(document);
                newDoc.setTableName("document");
                toJson.setObject(newDoc);
                toJson.setMsg("document");
                toJson.setFlag(0);
            } else {
                toJson.setMsg("新建失败，请联系管理员！");
                toJson.setFlag(1);
            }
        } catch (Exception e) {
            e.printStackTrace();
            toJson.setFlag(1);
            toJson.setMsg("新建失败，请联系管理员！");
        }
        return toJson;
    }


    public ToJson<Object> saveDocument2(Users user, Integer fflowId, Integer fflowStep, String fprcsId, String frunName, DocumentModelWithBLOBs document, HttpServletRequest request, String fromRunId, String attachmentId, String attachmentName
    ) {
        ToJson<Object> toJson = new ToJson<Object>();
        try {
            String cureTime = DateFormat.getCurrentTime2();
            document.setPrintDate(cureTime);

            String sqlType = "xoa" + (String) request.getSession().getAttribute(
                    "loginDateSouse"); //当前库

            ToJson<FlowFast> flowFastToJson = wfeFlowRunInfo.workFastAdd(user, fflowId, fflowStep, fprcsId, "", request, sqlType, frunName, null);


            if (flowFastToJson.isFlag()) {
                FlowFast fast = (FlowFast) flowFastToJson.getObject();
                Integer runId = fast.getFlowRun().getRunId(); //xin

                Integer flowId = fast.getFlowRun().getFlowId();
                FlowRun flowRun2 = new FlowRun();
                flowRun2.setRunId(runId);
                flowRun2.setAttachmentId(attachmentId);
                flowRun2.setAttachmentName(attachmentName);
                wfeFlowRunMapper.updateFu(flowRun2);

                if (document.getRunId() != null) {
                    //切回发公文的库
                    String firstDBSource = "xoa" + document.getTransferOrg();
                    // 数据库切换
                    ContextHolder.setConsumerType(firstDBSource);
                    Map map = new HashMap();
                    map.put("runId", document.getRunId());
                    //修改附件
                    FlowRun flowRun = wfeFlowRunMapper.find(map);

                    if (flowRun != null) {
                        //复制流程附件
                        documentOrgService.copyWordAndAIPFile(flowRun, null, firstDBSource, sqlType);
                        map.clear(); //清空
                        map.put("attachmentId", flowRun.getAttachmentId());
                        map.put("attachmentName", flowRun.getAttachmentName());
                        map.put("runId", runId);

                        //切回当前库
                        ContextHolder.setConsumerType(sqlType);
                        wfeFlowRunMapper.updateAttachment(map);

                        DocumentOrgWithBLOBs documentOrgWithBLOBs = new DocumentOrgWithBLOBs();
                        documentOrgWithBLOBs.setId(document.getId());
                        documentOrgWithBLOBs.setRunId(runId);
                        documentOrgWithBLOBs.setFlowId(flowId);
                        documentOrgMapper.updateByPrimaryKeySelective(documentOrgWithBLOBs);
                    }
                }


                document.setRunId(runId); //新
                document.setFlowId(flowId);
                Date date = new Date();
                document.setTitle(StringUtils.checkNull(document.getTitle()) ? fast.getFlowRun().getRunName() : document.getTitle());
                //SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                //String time = sdf.format(date);
                document.setcTime(date);
               /* Integer check = documentModelMapper.checkRunId(runId);
                if (check!=null&&1==check){
                    toJson.setMsg("重号，请重试！");
                    toJson.setFlag(1);
                    return toJson;
                }*/
                DocumentModelWithBLOBs documentModel =null;
                if(!StringUtils.checkNull(fromRunId)){//lsa添加判断
                    documentModel=documentModelMapper.checkRunIds(Integer.parseInt(fromRunId));
                    FileUploadUtil fileUploadUtil=new FileUploadUtil();
                    //1、直接上传的pdf，则复制pdf文件至pdf文件。2、正文转的pdf之后进行分发。则先复制pdf正文至aipFile。后将清稿正文存放到mainFile和存档originFile
                    if(!StringUtils.checkNull(documentModel.getMainAipFile())){
                        List<Attachment> aipFiles = GetAttachmentListUtils.returnAttachment(documentModel.getMainAipFileName(), documentModel.getMainAipFile(), sqlType, "document");
                        List<Attachment> aipAtt = fileUploadUtil.copyFiles(aipFiles, sqlType, "document", "document");
                        for (Attachment att : aipAtt) {
                            enclosureService.saveAttachment(att);
                        }
                        Object[] o3 = FileUploadUtil.reAttachment(aipAtt);
                        document.setMainAipFile(o3[0].toString().split(",")[0]);
                        document.setMainAipFileName(o3[1].toString().split("\\*")[0]);
                        //定稿正文
                        if(!StringUtils.checkNull(documentModel.getMainClearFile())){
                            List<Attachment> clearFiles = GetAttachmentListUtils.returnAttachment(documentModel.getMainClearFileName(), documentModel.getMainClearFile(), sqlType, "document");
                            List<Attachment> clearAtt = fileUploadUtil.copyFiles(clearFiles, sqlType, "document", "document");
                            for (Attachment att : clearAtt) {
                                enclosureService.saveAttachment(att);
                            }
                            Object[] o = FileUploadUtil.reAttachment(clearAtt);
                            document.setMainFile(o[0].toString().split(",")[0]);
                            document.setMainFileName(o[1].toString().split("\\*")[0]);
                            //存档正文
                            List<Attachment> originAtt = fileUploadUtil.copyFiles(clearAtt, sqlType, "document", "document");
                            for (Attachment att : originAtt) {
                                enclosureService.saveAttachment(att);
                            }
                            Object[] o2 = FileUploadUtil.reAttachment(originAtt);
                            document.setMainOriginFile(o2[0].toString().split(",")[0]);
                            document.setMainOriginFileName(o2[1].toString().split("\\*")[0]);
                        }
                    }else{//pdf正文为空则存编辑版的正文---存至mainFile-并复制存档到originFile
                        List<Attachment> documents = GetAttachmentListUtils.returnAttachment(documentModel.getMainFileName(), documentModel.getMainFile(), sqlType, "document");
                        List<Attachment> mainAtt = fileUploadUtil.copyFiles(documents, sqlType, "document", "document");
                        for (Attachment att : mainAtt) {
                            enclosureService.saveAttachment(att);
                        }
                        Object[] o = FileUploadUtil.reAttachment(mainAtt);
                        document.setMainFile(o[0].toString().split(",")[0]);
                        document.setMainFileName(o[1].toString().split("\\*")[0]);
                        //存档正文
                        List<Attachment> originAtt = fileUploadUtil.copyFiles(documents, sqlType, "document", "document");
                        for (Attachment att : originAtt) {
                            enclosureService.saveAttachment(att);
                        }
                        Object[] o2 = FileUploadUtil.reAttachment(originAtt);
                        document.setMainOriginFile(o2[0].toString().split(",")[0]);
                        document.setMainOriginFileName(o2[1].toString().split("\\*")[0]);
                    }
                    document.setPages(documentModel.getPages());
                    document.setContent(documentModel.getContent());
                }
                // GetAttachmentListUtil.returnAttachment(documentModel.getMainAipFileName(),documentModel.getMainAipFile(),sqlType,);
                String firstDBSource = "xoa" + document.getTransferOrg();
                // 数据库切换
                ContextHolder.setConsumerType(firstDBSource);
                Map map = new HashMap();
                map.put("runId", document.getRunId());
                //修改附件
                FlowRun flowRun = wfeFlowRunMapper.find(map);
                DocumentOrg documentOrg = new DocumentOrg();


                map.clear(); //清空
                map.put("attachmentId", flowRun.getAttachmentId());
                map.put("attachmentName", flowRun.getAttachmentName());
                map.put("runId", runId);
                //切回当前库
                ContextHolder.setConsumerType(sqlType);
                wfeFlowRunMapper.updateAttachment(map);
            /*    if(documentModel!=null){//lsa添加判断
                    List<String> list = documentOrgService.copyWordAndAIPFile2(flowRun, null, documentModel, sqlType, sqlType);
                    if (list != null && !list.isEmpty()) {
                        document.setMainAipFile(list.get(0));
                        String mainAipFileName = list.get(1);
                        if(!StringUtils.checkNull(mainAipFileName)){//将pdf的后缀转换为小写
                            String substring = mainAipFileName.substring(0, mainAipFileName.lastIndexOf("."))
                                    +mainAipFileName.substring(mainAipFileName.lastIndexOf(".")).toLowerCase();
                            document.setMainAipFileName(substring);
                        }
                    }
                }*/
                int result = documentModelMapper.insertSelective(document);
                DocumentModelWithBLOBs newDoc = documentModelMapper.selectByPrimaryKey(document);
                newDoc.setTableName("document");
                toJson.setObject(newDoc);
                toJson.setMsg("document");
                toJson.setFlag(0);
            } else {
                toJson.setMsg("新建失败，请联系管理员！");
                toJson.setFlag(1);
            }
        } catch (Exception e) {
            e.printStackTrace();
            toJson.setFlag(1);
            toJson.setMsg("新建失败，请联系管理员！");
        }
        return toJson;
    }


    public int deleteDocument(DocumentModelWithBLOBs document) {
        int result = documentModelMapper.deleteByPrimaryKey(document);
        return result;
    }

    public int updateDocument(DocumentModelWithBLOBs document) {
        int result = documentModelMapper.updateByPrimaryKeySelective(document);
        return result;
    }

    public DocumentModelWithBLOBs selectDocumentById(HttpServletRequest request,
                                                     DocumentModelWithBLOBs document) {
        List<SealWithBLOBs> sealByUser = sealService.getSealByUser(request);
        DocumentModelWithBLOBs resultDocument = documentModelMapper.selectByPrimaryKey(document);
        DocumentModel documentEditPriv = documentModelMapper.getDocumentEditPriv(document.getId());
        if (null != documentEditPriv) {
            FlowRun flowRun = wfeFlowRun.find(resultDocument.getRunId());
            if (!StringUtils.checkNull(flowRun.getEndTime())){
                resultDocument.setDocumentEditPrivDetail("");
                resultDocument.setDocumentEditPriv(0);

            }else{
                resultDocument.setDocumentEditPriv(documentEditPriv.getDocumentEditPriv() == null ? 0 : documentEditPriv.getDocumentEditPriv());
                resultDocument.setDocumentEditPrivDetail(documentEditPriv.getDocumentEditPrivDetail() == null ? "" : documentEditPriv.getDocumentEditPrivDetail());
            }
        }
        resultDocument.setSealWithBLOBs(sealByUser);
        String company = "";
        if (!StringUtils.checkNull((String) request.getSession().getAttribute("loginDateSouse")) && !"null".equals((String) request.getSession().getAttribute("loginDateSouse")) && request.getSession().getAttribute("loginDateSouse") != null) {
            company = (String) request.getSession().getAttribute("loginDateSouse");
        } else {
            company = "1001";
        }
        // 获取word的atturl
        List<Attachment> attachments = null;
        resultDocument.setWordAttUrl("");
        if (!StringUtils.checkNull(resultDocument.getMainFileName()) && !StringUtils.checkNull(resultDocument.getMainFile())) {
            attachments = GetAttachmentListUtil.returnAttachment(resultDocument.getMainFileName(), resultDocument.getMainFile(), "xoa" + company, "document");
            if (attachments.size() > 0) {
                for (int i = 0; i < attachments.size(); i++) {
                    if (this.chechFileExists("xoa" + company, "document", attachments.get(i))) {
                        resultDocument.setWordAttUrl(attachments.get(i).getAttUrl());
                    }
                }
            }
        } else {
            if (null != document.getFlowId()) {
                TemplateModule templateModule = templateModuleMapper.getTemplateByFlowId(document.getFlowId());
                if (templateModule != null) {
                    attachments = GetAttachmentListUtil.returnAttachment(templateModule.getAttachmentName(), templateModule.getAttachmentId(), "xoa" + company, "template");
                    // 创建存储新附件的list
                    List<Attachment> newAttachmentList = new ArrayList<Attachment>();
                    // 文件拷贝
                    try {
                        this.copyFiles("document","xoa"+ company, newAttachmentList, attachments,"template");
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    if (attachments.size() > 0) {
                        for (int i = 0; i < attachments.size(); i++) {
                            if (this.chechFileExists("xoa" + company, "template", attachments.get(i))) {
                                resultDocument.setWordAttUrl(newAttachmentList.get(i).getAttUrl());
                            }
                        }
                    }
                }
            }

        }
        // 获取aip的atturl
        resultDocument.setAipAttUrl("");
        if (!StringUtils.checkNull(resultDocument.getMainAipFile()) && !StringUtils.checkNull(resultDocument.getMainAipFileName())) {
            attachments = GetAttachmentListUtil.returnAttachment(resultDocument.getMainAipFileName(), resultDocument.getMainAipFile(), "xoa" + company, "document");
            if (attachments.size() > 0) {
                for (int i = 0; i < attachments.size(); i++) {
                    if (this.chechFileExists("xoa" + company, "document", attachments.get(i))) {
                        resultDocument.setAipAttUrl(attachments.get(i).getAttUrl());
                    }
                }
            }
        }
        // 获取原始正文的atturl
        resultDocument.setMainOriginAttUrl("");
        if (!StringUtils.checkNull(resultDocument.getMainOriginFile()) && !StringUtils.checkNull(resultDocument.getMainOriginFileName())) {
            attachments = GetAttachmentListUtil.returnAttachment(resultDocument.getMainOriginFileName(), resultDocument.getMainOriginFile(), "xoa" + company, "document");
            if (attachments.size() > 0) {
                for (int i = 0; i < attachments.size(); i++) {
                    if (this.chechFileExists("xoa" + company, "document", attachments.get(i))) {
                        resultDocument.setMainOriginAttUrl(attachments.get(i).getAttUrl());
                    }
                }
            }
        }
        // 获取清稿正文的atturl
        resultDocument.setMainClearAttUrl("");
        if (!StringUtils.checkNull(resultDocument.getMainClearFile()) && !StringUtils.checkNull(resultDocument.getMainClearFileName())) {
            attachments = GetAttachmentListUtil.returnAttachment(resultDocument.getMainClearFileName(), resultDocument.getMainClearFile(), "xoa" + company, "document");
            if (attachments.size() > 0) {
                for (int i = 0; i < attachments.size(); i++) {
                    if (this.chechFileExists("xoa" + company, "document", attachments.get(i))) {
                        resultDocument.setMainClearAttUrl(attachments.get(i).getAttUrl());
                    }
                }
            }
        }
        return resultDocument;
    }

    @Override
    public List<DocumentModelWithBLOBs> selectDocAll(
            DocumentModelWithBLOBs document) {
        return documentModelMapper.selectDocAll(document);
    }

    public final String numberZero = "0";
    public final String numberOne = "1";
    public final String numberTwo = "2";

    @Override
    public ToJson<DocumentModelWithBLOBs> seleDocSendReceive(
            String documentType, String curUserID, String allUserID, String dispatchType, String printDate,
            HttpServletRequest request, Integer page, Integer pageSize,
            Boolean useFlag) {
        Cookie redisSessionId = CookiesUtil.getCookieByName(request, "redisSessionId");
        String sqlType = "xoa"
                + (String) request.getSession().getAttribute("loginDateSouse");
        Users users = SessionUtils.getSessionInfo(request.getSession(),
                Users.class, new Users(), redisSessionId);
        ToJson<DocumentModelWithBLOBs> documentModelWithBLOBsToJson = new ToJson<DocumentModelWithBLOBs>();
        if (StringUtils.checkNull(documentType)) {
            documentModelWithBLOBsToJson.setFlag(1);
            documentModelWithBLOBsToJson.setMsg("缺少必要参数");
        }
        Map<String, Object> objectMap = new HashMap<String, Object>();
        PageParams pageParams = new PageParams();
        pageParams.setUseFlag(useFlag);
        pageParams.setPage(page);
        pageParams.setPageSize(pageSize);
        /*objectMap.put("page", page);
        objectMap.put("pageSize", pageSize);*/
        objectMap.put("dispatchType", dispatchType);
        objectMap.put("printDate", printDate);

        objectMap.put("page", pageParams);
        objectMap.put("documentType", documentType);
        if (numberZero.equals(curUserID)) {
            objectMap.put("flowStatus", "0");
            objectMap.put("curUserID", users.getUserId());
        } else if (numberOne.equals(curUserID)) {
            objectMap.put("flowStatus", "1");
            objectMap.put("allUserID", users.getUserId());
        } else if (numberTwo.equals(curUserID)) {
            objectMap.put("creater", users.getUserId());
        }

        List<DocumentModelWithBLOBs> documentModelWithBLOBs = documentModelMapper
                .seleDocSendReceive(objectMap);
        if (documentModelWithBLOBs != null && documentModelWithBLOBs.size() > 0) {
            Iterator<DocumentModelWithBLOBs> iterator = documentModelWithBLOBs
                    .iterator();
            while (iterator.hasNext()) {

                DocumentModelWithBLOBs modelWithBLOBs = iterator.next();
                modelWithBLOBs.setUserName(usersMapper
                        .getUsernameByUserId(modelWithBLOBs.getCreater()));
                FlowRunPrcs flowRunPrcs = flowRunPrcsMapper
                        .selectqueryByRunId(modelWithBLOBs.getFlowPrcs(),
                                modelWithBLOBs.getRunId());
                // ToJson<FlowFast> flowRunPrcsToJson=
                // workService.workFastAdd(users,modelWithBLOBs.getFlowId(),flowRunPrcs.getPrcsId(),flowRunPrcs.getFlowPrcs().toString(),flowRunPrcs.getRunId().toString(),request,sqlType);
                // modelWithBLOBs.setFlowFastToJson((FlowFast)
                // flowRunPrcsToJson.getObject());
                FlowProcess flowProcess = flowProcessMapper.findPrcessName(
                        modelWithBLOBs.getFlowId(),
                        Integer.parseInt(modelWithBLOBs.getFlowPrcs()));
                modelWithBLOBs.setPrcsName(flowProcess.getPrcsName());
                modelWithBLOBs.setPrcsId(flowRunPrcs.getPrcsId().toString());
                FlowRunPrcs flowRunPrcsOne = flowRunPrcsMapper
                        .selectqueryByRunId("2",
                                modelWithBLOBs.getRunId());
                if (flowRunPrcsOne != null) {
                    modelWithBLOBs.setDraftType("1");//0是草稿//1是转交
                } else {
                    modelWithBLOBs.setDraftType("0");
                }

            }
            documentModelWithBLOBsToJson.setFlag(0);
            documentModelWithBLOBsToJson.setMsg("ok");
            documentModelWithBLOBsToJson.setObj(documentModelWithBLOBs);
            documentModelWithBLOBsToJson.setTotleNum(pageParams.getTotal());
        }

        return documentModelWithBLOBsToJson;
    }

    /**
     * 规则常量
     */

    // 短年份
    private final String SHOT_YEAR = "YY";
    // 全年份
    private final String All_YEAR = "ALL_YY";
    // 日期
    private final String DATE = "DATE";
    // 日期带时分秒
    private final String DATE_TIME = "DATE_TIME";
    // 01 02 日
    private final String H_MOS = "H_MOS";
    // 1 2 日
    private final String H_MO = "H_MO";
    // 01 02 月份
    private final String MONTHS = "MONTHS";
    // 1 2 月份
    private final String MONTH = "MONTH";
    // 计数器
    private final String COUNTER = "COUNTER";


    /**
     * @param documentType 公文类型 0 发文，1 收文
     * @param title        公文名称
     * @param flowId       所属流程
     * @param dispatchType 文种类型
     * @param urgency      紧急程度
     * @param secrecy      机密等级
     * @param userId       创建人userId
     * @param deptId       部门Id
     * @param createTime   创建时间
     * @param status       状态
     * @param request
     * @return
     */
    @Override
    public BaseWrappers selectDocSelective(Integer documentType,
                                           String title,
                                           Integer flowId,
                                           String dispatchType,
                                           String urgency,
                                           String secrecy,
                                           String userId,
                                           String deptId,
                                           String createTime,
                                           Integer status, PageParams pageParams, HttpServletRequest request, Integer runId) {
        BaseWrappers baseWrappers = new BaseWrappers();
        String workLevel = request.getParameter("workLevel");
        String items = request.getParameter("items");
        String searchValues = request.getParameter("searchValues");
        Map<String, Object> param = new HashMap<String, Object>();
        param.put("documentType", documentType);
        param.put("title", title);
        param.put("flowId", flowId);
        param.put("dispatchType", dispatchType);
        param.put("urgency", urgency);
        param.put("secrecy", secrecy);
        param.put("userId", userId);
        param.put("deptId", deptId);
        param.put("createTime", createTime);
        param.put("status", status);
        param.put("runId", runId);
        param.put("workLevel", workLevel);
        if (!StringUtils.checkNull(items)){
            String [] itemArray = items.split(",");
            String [] searchValueArray = searchValues.split(",");
            String tableName = "flow_data_"+flowId;
            Cookie redisSessionId = CookiesUtil.getCookieByName(request, "redisSessionId");
            String sqlType = SessionUtils.getSessionInfo(request.getSession(), "loginDateSouse", String.class, redisSessionId);
            String company = "xoa" + sqlType;
            param.put("tableName", tableName);
            param.put("tableSchema", company);
            List<String> columns = workMapper.showColumns(param);
            List<String> itemList = new ArrayList<String>();
            for (int i=0,len=itemArray.length;i<len;i++){
                if (columns.contains(itemArray[i])){
                    itemList.add(itemArray[i]);
                    param.put(itemArray[i]+i,searchValueArray[i]);
                }
            }
            if (itemList.size()>0){
                param.put("itemList",itemList);
            }
        }
        param.put("page", pageParams);
        List<DocumentModelFlowRunPrcs> selectiveDoc = documentModelMapper.querySelectDoc(param);
        baseWrappers.setDatas(selectiveDoc);
        baseWrappers.setFlag(true);
        baseWrappers.setTotal(pageParams.getTotal());
        return baseWrappers;
    }


    @Override
    public BaseWrappers selWillDocSendOrReceive(HttpServletRequest request, String documentType, String dispatchType, String printDate, String title, Integer docStatus, Integer page, Integer pageSize, Integer prcsFlag,String state,String beginTime,String endTime) {
        BaseWrappers wrappers = new BaseWrappers();
        wrappers.setStatus(true);
        wrappers.setFlag(false);
        String flowId = request.getParameter("flowId");
        Cookie redisSessionId = CookiesUtil.getCookieByName(request, "redisSessionId");
        Users users = SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users(), redisSessionId);
        if (StringUtils.checkNull(users.getUserId())) {
            wrappers.setMsg("用户信息过期");
            return wrappers;
        }
        if (StringUtils.checkNull(dispatchType)) {
            dispatchType = null;
        }
        if (StringUtils.checkNull(printDate)) {
            printDate = null;
        }
        if (StringUtils.checkNull(title)) {
            title = null;
        }

        page = (page - 1) * pageSize;
        Map<String, Object> param = new HashMap<String, Object>();
        param.put("userId", users.getUserId());
        param.put("documentType", documentType);
        param.put("printDate", printDate);
        param.put("dispatchType", dispatchType);
        param.put("page", page);
        param.put("pageSize", pageSize);
        param.put("prcsFlag", prcsFlag);
        param.put("title", title);
        param.put("docStatus", docStatus);
        param.put("flowId", flowId);
        param.put("state", state);
        param.put("beginTime", beginTime);
        param.put("endTime", endTime);
        List<DocumentModelFlowRunPrcs> datas = documentModelMapper.selWillDocSendOrReceive(param);
        // 时限
        for (DocumentModelFlowRunPrcs d : datas) {
            if (StringUtils.checkNull(d.getBranchCount())){
                d.setBranchCount("0");
            }
            Users users1 = usersMapper.SimplefindUsersByuserId(d.getCreater());
            if (users1 != null) {
                d.setCreaterName(users1.getUserName());
            }
            SysCode gwtype = sysCodeMapper.getSingleCode("GWTYPE", d.getDispatchType());
            if (gwtype != null) {
                d.setCodeName(gwtype.getCodeName());
            }
            //获取发起人
            d.setAvatar(users1.getAvatar() == null ? "" : users1.getAvatar());
            //取当前步骤
            Map<String, Object> m = new HashMap<String, Object>();
            m.put("runId", d.getRunId());
            FlowRun flowRun = wfeFlowRunMapper.find(m);
            //查询流程最后一步
            Map<String, Object> map1 = new HashMap<String, Object>();
            map1.put("prcsId", d.getStep() + 1);
            map1.put("runId", d.getRunId());
            List<FlowRunPrcs> nextFlowRunPrcsList = wfeFlowRunPrcsMapper.findNextFrp(map1);
            List<FlowRunPrcs> maxFrp = wfeFlowRunPrcsMapper.findMaxFrp(d.getRunId());
            //查询下一步的流程
            //查询流程最后一步
            if (nextFlowRunPrcsList.size() == 1) {
                FlowRunPrcs flowRunPrcs1 = nextFlowRunPrcsList.get(0);
                d.setNextPrcsFlag(flowRunPrcs1.getPrcsFlag());
                if (flowRunPrcs1.getPrcsFlag().equals("1")) {
                    d.setState1("已转交，下一步未接收");
                } else if (flowRunPrcs1.getPrcsFlag().equals("2")) {
                    d.setState1("已转交，下一步办理中");
                } else if (flowRunPrcs1.getPrcsFlag().equals("3")) {
                    d.setState1("已转交，下一步已转交");
                } else if (flowRunPrcs1.getPrcsFlag().equals("4")) {
                    d.setState1("已转交，下一步已办结");
                }
            } else {
                List<String> list1 = new ArrayList<String>();
                int one = 0;
                int two = 0;
                int three = 0;
                int four = 0;
                for (FlowRunPrcs flowRunPrcs1 : nextFlowRunPrcsList) {
                    if (flowRunPrcs1.getPrcsFlag().equals("1")) {
                        one++;
                    } else if (flowRunPrcs1.getPrcsFlag().equals("2")) {
                        two++;
                    } else if (flowRunPrcs1.getPrcsFlag().equals("3")) {
                        three++;
                    } else if (flowRunPrcs1.getPrcsFlag().equals("4")) {
                        four++;
                    }
                }
                if (one == nextFlowRunPrcsList.size()) {
                    d.setState1("已转交，下一步未接收");
                    d.setNextPrcsFlag("1");
                } else if (three == nextFlowRunPrcsList.size()) {
                    d.setState1("已转交，下一步已办结");
                    d.setNextPrcsFlag("3");
                } else {
                    d.setState1("已转交，下一步办理中");
                    d.setNextPrcsFlag("2");
                }
                if(four>0){
                    d.setNextPrcsFlag("4");
                }
            }
            if (maxFrp.size() > 1) {
                d.setState2("1");
            } else {
                FlowRunPrcs flowRunPrcs3 = maxFrp.get(0);
                d.setState2("0");

                Map<String, Object> map = new HashMap<String, Object>();
                map.put("runId", flowRunPrcs3.getRunId());
                map.put("prcsId", flowRunPrcs3.getFlowPrcs());
                String prcsName = "第" + flowRunPrcs3.getPrcsId() + "步:" + flowProcessMapper.findPrcsName(map);
                d.setJbbz(String.valueOf(flowRunPrcs3.getPrcsId()));
                d.setBz(prcsName);
                d.setCurrentPeople(usersService.getUserNameById(flowRunPrcs3.getUserId()));
            }
            Map map2 = new HashMap();
            if (StringUtils.checkNull(flowRun.getEndTime())) {
                d.setState("执行中");
            } else {
                d.setState("已结束");
                d.setState1("流程已结束");
                //找出最后一步的审批人
                String finalapprovalUserId = flowProcessMapper.findFinalapprovalUserId(d.getRunId());
                map2.put("userid", finalapprovalUserId);
            }
            d.setMap(map2);

            // 超时计算方法  0-本步骤接收后开始计时,1-上一步骤转交后开始计时
            if ("0".equals(d.getTimeOutType())) {
                // 判断该步骤状态  1-未接收,2-办理中,3-转交下一步，下一步经办人无人接收,4-已办结,5-自由流程预设步骤,6-已挂起
                if (d.getPrFlag().equals(2)) {
                    if (!StringUtils.checkNull(d.getPrcsTime())) {
                        setTimeOutStr(d, DateFormat.getTime(d.getPrcsTime()));
                    }
                } else if (d.getPrFlag().equals(1)) {
                    if (!StringUtils.checkNull(d.getTimeOut())) {
                        d.setIfOutTime(true);
                        d.setTimeOutStr("计时未开始");
                    }
                }
            } else if ("1".equals(d.getTimeOutType())) {
                if (!d.getRealPrcsId().equals(1)) {
                    if (!d.getPrFlag().equals(3) && !d.getPrFlag().equals(4)) {
                        if (!StringUtils.checkNull(d.getCreateTime())) {
                            setTimeOutStr(d, DateFormat.getTime(d.getCreateTime()));
                        }
                    } else if (d.getPrFlag().equals(3)) {
                        d.setTimeOutStr("计时已结束");
                        d.setIfOutTime(true);
                    } else if (d.getPrFlag().equals(4)) {
                        d.setTimeOutStr("计时已结束");
                        d.setIfOutTime(true);
                    }
                }
            }
            if (d.getPrintDate().length() > 10) {
                d.setPrintDate(d.getPrintDate().substring(0, 10));
            }
            if (d.getPrcsTime() != null && !"".equals(d.getPrcsTime())) {
                String s = d.getPrcsTime();
                d.setPrcsTime(s.substring(0, s.length() - 2));
            }
            //将传阅的人按步骤号拼接
            Map map = new HashMap();
            map.put("prcsId", d.getStep());
            /*   map.put("flowPrcs",d.getRealPrcsId());*/
            map.put("runId", d.getRunId());
            String viewUser = "";
            List<FlowRunRead> flowRunReadList = toBeReadMapper.ReadFileIsRead(map);
            for (FlowRunRead flowRunRead : flowRunReadList) {
                viewUser += flowRunRead.getUserId() + ",";
            }
            d.setViewUser(viewUser);
            //查询当前步骤是否是并发步骤
            FlowProcess flowProcess = flowProcessMapper.findProcess(d.getFlowId(), d.getRealPrcsId());
            if(1==prcsFlag) {

                if (flowProcess != null && !StringUtils.checkNull(d.getBranchCount()) && "1".equals(flowProcess.getGatherNode())) {
                    //如果是并发节点
                    //找到当前flow_run_prcs
                    Map<String, Object> ma = new HashMap<String, Object>();
                    if (!"".equals(d.getStep()) && d.getStep() != null) {
                        Integer prcsId = Integer.valueOf(d.getStep());
                        ma.put("prcsId", prcsId - 1);
                    }
                    if (!"".equals(d.getRunId()) && d.getRunId() != null) {
                        Integer runId = Integer.valueOf(d.getRunId());
                        ma.put("runId", runId);
                    }
                    //查询上一步流程
                    List<FlowRunPrcs> list = wfeFlowRunPrcs.findByRunId1(ma);
                    if (!"".equals(d.getFlowPrcs()) && d.getFlowPrcs() != null) {
                        Integer flowPrcs = Integer.valueOf(d.getRealPrcsId());
                        ma.put("flowPrcs", flowPrcs);
                    }
                    if (!"".equals(d.getUserId()) && d.getUserId() != null) {
                        String userId = d.getUserId();
                        ma.put("userId", userId);
                    }

                    String branchCount = null;
                    for (FlowRunPrcs flowRunPrcs : list) {
                        if (StringUtils.checkNull(branchCount)) {
                            branchCount = flowRunPrcs.getBranchCount();
                        } else {
                            if (!StringUtils.checkNull(flowRunPrcs.getBranchCount())) {
                                branchCount = branchCount + "," + flowRunPrcs.getBranchCount();
                            }
                        }
                    }
                    if (!StringUtils.checkNull(branchCount)) {
                        String[] processStr = branchCount.split(",");
                        List<Integer> listPrcs = new ArrayList<Integer>();
                        List<Integer> listFlag = new ArrayList<Integer>();
                        listFlag.add(1);
                        listFlag.add(2);
                        //判断是否已办结
                        for (int i = 0; i < processStr.length; i++) {
                            if (!StringUtils.checkNull(processStr[i])) {
                                listPrcs.add(Integer.parseInt(processStr[i]));
                            }
                        }
                        Map<String, Object> mm = new HashMap<String, Object>();
                        if (!"".equals(d.getRunId()) && d.getRunId() != null) {
                            Integer runId = Integer.valueOf(d.getRunId());
                            mm.put("runId", runId);
                        }
                        if (!"".equals(d.getFlowPrcs()) && d.getFlowPrcs() != null) {
                            Integer flowPrcs = Integer.valueOf(d.getRealPrcsId());
                            mm.put("flowPrcs", flowPrcs);
                        }
                        mm.put("listFlag", listFlag);
                        mm.put("listPrcs", listPrcs);
                        Integer gatherNodePriv = wfeFlowRunPrcs.checkGatherNode(mm);
                        if (gatherNodePriv == null) {
                            d.setBranchCount("0");
                        } else {
                            d.setBranchCount("1");
                        }
                    }
                } else {
                    d.setBranchCount("0");
                }
            }
        }
        List<DocumentModelFlowRunPrcs> data = documentModelMapper.selWillDocSendOrReceiveCount(param);
        wrappers.setTotal(data.size());
        wrappers.setFlag(true);
        wrappers.setDatas(datas);
        return wrappers;
    }

    /**
     * 作者: 张航宁
     * 日期: 2017/9/21
     * 说明: 设置剩余或者超时时间
     */
    private void setTimeOutStr(DocumentModelFlowRunPrcs d, Integer time) {
        if (!StringUtils.checkNull(d.getTimeOut())) {
            // 获取限时时间和类型 hour是小时 day是天
            String[] split = d.getTimeOut().split(",");
            if (split.length == 2) {
                String timeCount = split[0];
                String timeType = split[1];
                // 判断是哪种类型的时间限制
                if (timeType.equals("hour")) {
                    // 总计办理时间时间戳
                    int i = (int) (Double.valueOf(timeCount) * 60 * 60);
                    // 超时时间
                    int outTimeEnd = time + i;
                    // 当前时间
                    int currentTime = (int) (System.currentTimeMillis() / 1000);
                    // 获取时间差 计算时间 并赋值
                    d.setTimeOutStr("时限" + timeCount + "小时，" + getTimeOutStr(outTimeEnd, currentTime, d));
                } else if (timeType.equals("day")) {
                    // 总计办理时间时间戳
                    int i = (int) (Double.valueOf(timeCount) * 24 * 60 * 60);
                    // 超时时间
                    int outTimeEnd = time + i;
                    // 当前时间
                    int currentTime = (int) (System.currentTimeMillis() / 1000);
                    // 获取时间差 计算时间 并赋值
                    d.setTimeOutStr("时限" + timeCount + "天，" + getTimeOutStr(outTimeEnd, currentTime, d));
                }
            }
        }
    }

    /**
     * 作者: 张航宁
     * 日期: 2017/9/20
     * 说明: 获取剩余或者超时时间
     */
    private String getTimeOutStr(int outTimeEnd, int currentTime, DocumentModelFlowRunPrcs d) {
        String s;
        if (outTimeEnd > currentTime) {
            int times = outTimeEnd - currentTime;
            s = "剩余" + DateFormat.returnTime(times);
            d.setIfOutTime(false);
        } else {
            int times = currentTime - outTimeEnd;
            s = "超时" + DateFormat.returnTime(times);
            d.setIfOutTime(true);
        }
        return s;
    }


    @Override
    public BaseWrappers selOverDocSendOrReceive(HttpServletRequest request, String documentType, String dispatchType, String printDate, String title, Integer docStatus, Integer page, Integer pageSize, Integer prcsFlag) {
        BaseWrappers wrappers = new BaseWrappers();
        wrappers.setStatus(true);
        wrappers.setFlag(false);
        /*if (StringUtils.checkNull(documentType)) {
            wrappers.setMsg("获取公文类型失败");
            return wrappers;
        }*/
        Cookie redisSessionId = CookiesUtil.getCookieByName(request, "redisSessionId");
        Users users = SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users(), redisSessionId);
        if (StringUtils.checkNull(users.getUserId())) {
            wrappers.setMsg("用户信息过期");
            return wrappers;
        }
        if (StringUtils.checkNull(dispatchType)) {
            dispatchType = null;
        }
        if (StringUtils.checkNull(printDate)) {
            printDate = null;
        }
        page = (page - 1) * pageSize;
        Map<String, Object> param = new HashMap<String, Object>();
        param.put("userId", users.getUserId());
        param.put("documentType", documentType);
        param.put("printDate", printDate);
        param.put("dispatchType", dispatchType);
        param.put("page", page);
        param.put("pageSize", pageSize);
        param.put("prcsFlag", prcsFlag);
        List<DocumentModelOverRun> datas = documentModelMapper.selOverDocSendOrReceive(param);
        for (DocumentModelOverRun d : datas) {
            Users users1 = usersMapper.SimplefindUsersByuserId(d.getCreater());
            if (users1 != null) {
                d.setCreaterName(users1.getUserName());
            }
        }
        Integer total = documentModelMapper.selOverDocSendOrReceiveCounts(param);
        wrappers.setTotal(total);
        wrappers.setFlag(true);
        wrappers.setDatas(datas);
        return wrappers;
    }

    //最新文件（公文 可传阅的 办结公文）
    @Override
    public BaseWrappers selMyDocument(HttpServletRequest request, String documentType, String dispatchType, String printDate, String title, Integer docStatus, Integer page, Integer pageSize, Integer prcsFlag) {
        BaseWrappers wrappers = new BaseWrappers();
        wrappers.setStatus(true);
        wrappers.setFlag(false);
        Cookie redisSessionId = CookiesUtil.getCookieByName(request, "redisSessionId");
        Users users = SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users(), redisSessionId);
        if (StringUtils.checkNull(users.getUserId())) {
            wrappers.setMsg("用户信息过期");
            return wrappers;
        }
        Map<String, Object> param = new HashMap<String, Object>();
        PageParams pageParams = new PageParams();
        pageParams.setUseFlag(true);
        pageParams.setPage(page);
        pageParams.setPageSize(pageSize);
        param.put("userId", users.getUserId());
        param.put("page", pageParams);
        List<DocumentModelOverRun> datas = documentModelMapper.selWillDocSendOrReceivedz(param);
        // 时限
        for (DocumentModelOverRun d : datas) {
            Users users1 = usersMapper.SimplefindUsersByuserId(d.getCreater());
            if (users1 != null) {
                d.setCreaterName(users1.getUserName());
            }
            //将传阅的人按步骤号拼接
            Map map = new HashMap();
            map.put("prcsId", d.getStep());
            map.put("runId", d.getRunId());
            String viewUser = "";
            List<FlowRunRead> flowRunReadList = toBeReadMapper.queryFileIsRead(map);
            for (FlowRunRead flowRunRead : flowRunReadList) {
                viewUser += flowRunRead.getUserId() + ",";
                if(users.getUserId().equals(flowRunRead.getUserId())){
                    d.setReadFlag(flowRunRead.getReadFlag() == 1 ? true : false);
                }
            }
            d.setViewUser(viewUser);
        }
        wrappers.setTotal(pageParams.getTotal());
        wrappers.setFlag(true);
        wrappers.setDatas(datas);
        return wrappers;
    }

    @Override
    public BaseWrappers selMyDocSendOrReceive(HttpServletRequest request, String documentType, String dispatchType, String printDate, String title, Integer docStatus, Integer page, Integer pageSize) {
        BaseWrappers wrappers = new BaseWrappers();
        wrappers.setStatus(true);
        wrappers.setFlag(false);
        if (StringUtils.checkNull(documentType)) {
            wrappers.setMsg("获取公文类型失败");
            return wrappers;
        }
        Cookie redisSessionId = CookiesUtil.getCookieByName(request, "redisSessionId");
        Users users = SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users(), redisSessionId);
        if (StringUtils.checkNull(users.getUserId())) {
            wrappers.setMsg("用户信息过期");
            return wrappers;
        }
        if (StringUtils.checkNull(dispatchType)) {
            dispatchType = null;
        }
        if (StringUtils.checkNull(printDate)) {
            printDate = null;
        }
        if (StringUtils.checkNull(title)) {
            title = null;
        }

        page = (page - 1) * pageSize;
        Map<String, Object> param = new HashMap<String, Object>();
        param.put("userId", users.getUserId());
        param.put("documentType", documentType);
        param.put("printDate", printDate);
        param.put("dispatchType", dispatchType);
        param.put("page", page);
        param.put("pageSize", pageSize);
        param.put("title", title);
        param.put("docStatus", docStatus);
        List<DocumentModelFlowRunPrcs> datas = documentModelMapper.selMyDocSendOrReceive(param);
        for (DocumentModelFlowRunPrcs d : datas) {
            if (d.getPrintDate().length() > 10) {
                d.setPrintDate(d.getPrintDate().substring(0, 10));
            }
            Users users1 = usersMapper.SimplefindUsersByuserId(d.getCreater());
            if (users1 != null) {
                d.setCreaterName(users1.getUserName());
            }
            SysCode gwtype = sysCodeMapper.getSingleCode("GWTYPE", d.getDispatchType());
            if (gwtype != null) {
                d.setCodeName(gwtype.getCodeName());
            }
            //大足教委提出已办公文和我的公文按钮要显示一致，因此添加此段代码用以前端判断
            Map<String, Object> m = new HashMap<String, Object>();
            m.put("runId", d.getRunId());
            FlowRun flowRun = wfeFlowRunMapper.find(m);
            if (!StringUtils.checkNull(flowRun.getEndTime())) {
                //找出最后一步的审批人
                String finalapprovalUserId = flowProcessMapper.findFinalapprovalUserId(d.getRunId());
                m.remove("runId");
                m.put("userid", finalapprovalUserId);
            }
            d.setMap(m);

        }
        Integer total = documentModelMapper.selMyDocSendOrReceiveCounts(param);
        wrappers.setTotal(total);
        wrappers.setFlag(true);
        wrappers.setDatas(datas);
        return wrappers;
    }

    /**
     * 督办公文
     *
     * @param request
     * @param documentType
     * @param dispatchType
     * @return
     */
    public BaseWrappers selOverseeTheOfficialDocument(HttpServletRequest request, String documentType, String dispatchType, String computationNumber, Integer page, Integer pageSize,
                                                      Boolean useFlag, String printDate, String title) {
        BaseWrappers wrappers = new BaseWrappers();
        wrappers.setStatus(true);
        wrappers.setFlag(false);
        Cookie redisSessionId = CookiesUtil.getCookieByName(request, "redisSessionId");
        Users users = SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users(), redisSessionId);
        if (StringUtils.checkNull(users.getUserId())) {
            wrappers.setMsg("用户信息过期");
            return wrappers;
        }
        if (StringUtils.checkNull(dispatchType)) {
            dispatchType = null;
        }
        if (StringUtils.checkNull(documentType)) {
            documentType = null;
        }
        String date = "";
        if (!StringUtils.checkNull(computationNumber)) {
            date = computationTime(computationNumber);
        } else {
            date = null;
        }
        Map<String, Object> objectMap = new HashMap<String, Object>();
        PageParams pageParams = new PageParams();
        pageParams.setUseFlag(useFlag);
        pageParams.setPage(page);
        pageParams.setPageSize(pageSize);
        objectMap.put("page", pageParams);
        objectMap.put("dispatchType", dispatchType);
        objectMap.put("documentType", documentType);
        objectMap.put("printDate", printDate);
        objectMap.put("title", title);
        objectMap.put("date", date);
        List<DocumentModelFlowRunPrcs> datas = documentModelMapper.selOverseeTheOfficialDocument(objectMap);
        for (DocumentModelFlowRunPrcs data : datas) {
            data.setCurUserId(data.getUserId()); //当前经办人ID
            objectMap.put("runId", data.getRunId());
            StringBuffer stringBuffer = new StringBuffer();
            for (DocumentModelFlowRunPrcs data2 : documentModelMapper.selOverseeTheOfficialDocument(objectMap)) {
                stringBuffer.append(data2.getUserId()).append(",");
            }
            data.setAllUserId(stringBuffer.toString()); //全部经办人ID


            data.setCurUserIdName(usersMapper.getUsernameByUserId(data.getCurUserId())); //当前经办人名
            data.setAllUserIdName(usersService.getUserNameById(data.getAllUserId())); //全部经办人名
            Users users1 = usersMapper.SimplefindUsersByuserId(data.getCreater());
            if (users1 != null) {
                data.setCreaterName(users1.getUserName());
            }
            SysCode gwtype = sysCodeMapper.getSingleCode("GWTYPE", data.getDispatchType());
            if (gwtype != null) {
                data.setCodeName(gwtype.getCodeName());
            }
        }
        wrappers.setTotal(pageParams.getTotal());
        wrappers.setFlag(true);
        wrappers.setDatas(datas);

        return wrappers;
    }

    @Override
    public BaseWrappers addDocSendSms(HttpServletRequest req, String cuName, String allName, String title, String classify, String flowId, String prcsId, String flowStep, String runId, String opFlag) {
        BaseWrappers wrappers = new BaseWrappers();
        Cookie redisSessionId = CookiesUtil.getCookieByName(req, "redisSessionId");
        Users users = SessionUtils.getSessionInfo(req.getSession(), Users.class, new Users(), redisSessionId);
        if (StringUtils.checkNull(users.getUserId())) {
            wrappers.setMsg("用户信息过期");
            return wrappers;
        }
        SmsBody smsBody = new SmsBody();
        smsBody.setFromId(users.getUserId());
        smsBody.setSmsType("70");
        smsBody.setContent(title);
        smsBody.setSendTime((int) (System.currentTimeMillis() / 1000));
        smsBody.setRemindUrl("/workflow/work/workform?opflag=" + opFlag + "&flowId=" + flowId + "&flowStep=" + flowStep + "&tableName=document" + "&tabId=" + "&runId=" + runId + "&prcsId=" + prcsId + "&isNomalType=false");
        String toId = "";
        if (numberZero.equals(classify)) {
            toId = cuName;
        } else if (numberOne.equals(classify)) {
            toId = allName;
        } else if (numberTwo.equals(classify)) {
            String[] all = allName.split(",");
            StringBuffer str = new StringBuffer();
            for (int i = 0; i < all.length; i++) {
                if (all[i].endsWith("undefined")) {
                    continue;
                } else if (!all[i].equals(cuName)) {
                    str.append(all[i]);
                    str.append(",");
                }
            }
            toId = cuName + "," + str.toString();
        }

        ToJson<SmsBody> smsBodyToJson = smsService.saveSms(smsBody, toId, "1", "0", "", "", "");
        if ("ok".equals(smsBodyToJson.getMsg())) {
            wrappers.setFlag(true);
            wrappers.setStatus(true);
        } else {
            wrappers.setFlag(false);
            wrappers.setStatus(true);
        }

        return wrappers;
    }

    /**
     * @作者：张航宁
     * @时间：2017/8/9
     * @介绍：查询是否可以编辑
     * @参数：id
     */
    @Override
    public ToJson<DocumentModel> getDocumentEditPriv(Integer id) {
        ToJson<DocumentModel> json = new ToJson<DocumentModel>();
        try {
            if (id != null) {
                DocumentModel documentEditPriv = documentModelMapper.getDocumentEditPriv(id);
                json.setObject(documentEditPriv);
                json.setFlag(0);
                json.setMsg("ok");
            }
        } catch (Exception e) {
            e.printStackTrace();
            json.setFlag(1);
            json.setMsg("err");
        }
        return json;
    }

    /**
     * 作者: 张航宁
     * 日期: 2017/9/26
     * 说明: 查询有时限的公文信息
     */
    @Override
    public BaseWrappers selectTimeOutDoc(HttpServletRequest request) {
        BaseWrappers wrappers = new BaseWrappers();
        Cookie redisSessionId = CookiesUtil.getCookieByName(request, "redisSessionId");
        Users users = SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users(), redisSessionId);
        if (StringUtils.checkNull(users.getUserId())) {
            wrappers.setMsg("用户信息过期");
            return wrappers;
        }

        Map<String, Object> param = new HashMap<String, Object>();

        param.put("userId", users.getUserId());
        param.put("page", 0);
        param.put("pageSize", 5);

        List<DocumentModelFlowRunPrcs> datas = documentModelMapper.selectTimeOutDoc(param);
        // 时限
        for (DocumentModelFlowRunPrcs d : datas) {
            // 超时计算方法  0-本步骤接收后开始计时,1-上一步骤转交后开始计时
            if (d.getTimeOutType().equals("0")) {
                // 判断该步骤状态  1-未接收,2-办理中,3-转交下一步，下一步经办人无人接收,4-已办结,5-自由流程预设步骤,6-已挂起
                if (d.getPrFlag().equals(2)) {
                    if (!StringUtils.checkNull(d.getPrcsTime())) {
                        setTimeOutStr(d, DateFormat.getTime(d.getPrcsTime()));
                    }
                } else if (d.getPrFlag().equals(1)) {
                    if (!StringUtils.checkNull(d.getTimeOut())) {
                        d.setTimeOutStr("计时未开始");
                        d.setIfOutTime(true);
                    }
                }
            } else if (d.getTimeOutType().equals("1")) {
                if (!d.getRealPrcsId().equals(1)) {
                    if (!d.getPrFlag().equals(3) && !d.getPrFlag().equals(4)) {
                        if (!StringUtils.checkNull(d.getCreateTime())) {
                            setTimeOutStr(d, DateFormat.getTime(d.getCreateTime()));
                        }
                    } else if (d.getPrFlag().equals(3)) {
                        d.setTimeOutStr("计时已结束,下一步经办人未接收");
                        d.setIfOutTime(true);
                    } else if (d.getPrFlag().equals(4)) {
                        d.setTimeOutStr("计时已结束,已结束");
                        d.setIfOutTime(true);
                    }
                }
            }
        }
        wrappers.setFlag(true);
        wrappers.setDatas(datas);
        return wrappers;
    }

    private final String One_Week = "oneWeek";// 一周
    private final String Second_Week = "secondWeek";// 二周
    private final String Third_Week = "thirdWeek";// 三周
    private final String One_Month = "oneMonth";// 一个月
    private final String Second_Month = "secondMonth";// 俩个月
    private final String Third_Month = "thirdMonth";// 三个月


    public String computationTime(String computationNumber) {

        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        Calendar c = Calendar.getInstance();
        String day = "";
        if (One_Week.equals(computationNumber)) {
            c.setTime(new Date());
            c.add(Calendar.DATE, +7);
            Date d = c.getTime();
            day = format.format(d);
        } else if (Second_Week.equals(computationNumber)) {
            c.setTime(new Date());
            c.add(Calendar.DATE, +14);
            Date d1 = c.getTime();
            day = format.format(d1);

        } else if (Third_Week.equals(computationNumber)) {
            c.setTime(new Date());
            c.add(Calendar.DATE, +21);
            Date d2 = c.getTime();
            day = format.format(d2);

        } else if (One_Month.equals(computationNumber)) {
            c.setTime(new Date());
            c.add(Calendar.MONTH, +1);
            Date m = c.getTime();
            day = format.format(m);

        } else if (Second_Month.equals(computationNumber)) {
            c.setTime(new Date());
            c.add(Calendar.MONTH, +2);
            Date m2 = c.getTime();
            day = format.format(m2);

        } else if (Third_Month.equals(computationNumber)) {
            c.setTime(new Date());
            c.add(Calendar.MONTH, +3);
            Date m3 = c.getTime();
            day = format.format(m3);

        }

        return day;
    }

    @Override
    public BaseWrappers<DocumentModelFlowRunPrcs> selDocByTitle(HttpServletRequest request, String title, PageParams pageParams) {
        BaseWrappers<DocumentModelFlowRunPrcs> wrappers = new BaseWrappers<>();
        Map<String, Object> map = new HashMap<>();
        Cookie redisSessionId = CookiesUtil.getCookieByName(request, "redisSessionId");
        Users users = SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users(), redisSessionId);
        map.put("title", title);
        map.put("userId", users.getUserId());
        map.put("page", pageParams);
        try {
            List<DocumentModelFlowRunPrcs> documentModelFlowRunPrcs = documentModelMapper.selDocByTitle(map);
            if (documentModelFlowRunPrcs != null) {
                for (DocumentModelFlowRunPrcs data : documentModelFlowRunPrcs) {
                    Users users1 = usersMapper.SimplefindUsersByuserId(data.getCreater());
                    if (users1 != null) {
                        data.setCreaterName(users1.getUserName());
                    }
                    SysCode gwtype = sysCodeMapper.getSingleCode("GWTYPE", data.getDispatchType());
                    if (gwtype != null) {
                        data.setCodeName(gwtype.getCodeName());
                    }
                }
                wrappers.setMsg("查询成功！");
                wrappers.setDatas(documentModelFlowRunPrcs);
                wrappers.setFlag(true);
            } else {
                wrappers.setMsg("未查询到数据！");
                wrappers.setFlag(true);
            }
        } catch (Exception e) {
            e.printStackTrace();
            wrappers.setMsg(e.getMessage());
        }
        return wrappers;
    }


    @Override
    public DocumentModel checkRunId(Integer runId) {
        return documentModelMapper.checkRunId(runId);
    }


    public boolean chechFileExists(String company, String module, Attachment attachment) {
        //读取配置文件
        ResourceBundle rb = ResourceBundle.getBundle("upload");
        String osName = System.getProperty("os.name");
        StringBuffer sb = new StringBuffer();
        if (osName.toLowerCase().startsWith("win")) {
            //sb=sb.append(rb.getString("upload.win"));
            //判断路径是否是相对路径，如果是的话，加上运行的路径
            String uploadPath = rb.getString("upload.win");
            if (uploadPath.indexOf(":") == -1) {
                //获取运行时的路径
                String basePath = this.getClass().getClassLoader().getResource(".").getPath() + File.pathSeparator;
                //获取截取后的路径
                String str2 = "";
                if (basePath.indexOf("/xoa") != -1) {
                    //获取字符串的长度
                    int length = basePath.length();
                    //返回指定字符在此字符串中第一次出现处的索引
                    int index = basePath.indexOf("/xoa");
                    //从指定位置开始到指定位置结束截取字符串
                    str2 = basePath.substring(0, index);
                }
                sb = sb.append(str2 + "/xoa");
            }
            sb.append(uploadPath);
        } else {
            sb = sb.append(rb.getString("upload.linux"));
        }


        //---------------------------------判断是否为Linux开始-------------------------------------



        String attachmentName = attachment.getAttachName();
        try {
            int codeLength = attachmentName.getBytes("UTF-8").length;
            String type = attachmentName.substring(attachmentName.lastIndexOf("."));
            if(codeLength>230&&osName.toLowerCase().startsWith("linu")){//判断
                String s = (new BASE64Encoder()).encodeBuffer((attachmentName.substring(0,attachmentName.lastIndexOf("."))).getBytes(StandardCharsets.UTF_8));
                String regEx=("[\\s\\\\/:\\*\\?\\\"<>\\|]");
                attachmentName=(Pattern.compile(regEx).matcher(s).replaceAll("").trim().substring(0,100))+type;
            }
        }catch (Exception e){

        }


        //---------------------------------判断是否为Linux结束-------------------------------------




        String path = sb.toString() + System.getProperty("file.separator") + company +
                System.getProperty("file.separator") + module + System.getProperty("file.separator") + attachment.getYm() + System.getProperty("file.separator") + attachment.getAttachId() + "." + attachmentName;
        File f = new File(path);
        if (f.exists()) {
            return true;
        }
        return false;
    }

    //获取未使用的文号
    public ToJson unUseNo(HttpServletRequest request, SysRuleModel sysRuleModel, Integer flowId) {
        ToJson json = new ToJson<>();
        List<List<Map<String, String>>> maps=new ArrayList<>();
        String tableName = "flow_data_" + flowId;
        StringBuffer sb = new StringBuffer();
        List<FlowFormType> allFlowForm = wfeFormTypeMapper.getFrombyFlowId(flowId);
        FlowFormType flowFormType = allFlowForm.get(0);
        String sqlType = "xoa"+(String) request.getSession().getAttribute(
                "loginDateSouse");
        //获取该表数据库中的所有的列
        Map<String, Object> param = new HashMap<String, Object>();
        param.put("tableName", tableName);
        param.put("tableSchema", sqlType);
        //获取该表所有的列
        String[] datas = request.getParameter("datas").split(",");
        List<String> columns = workMapper.showColumns(param);
        String expression = sysRuleModel.getExpression();
        String jiequ=expression.substring(0, expression.indexOf("[COUNTER]"));
        //[COUNTER]后的规则
        String after=expression.substring(jiequ.length()+9, expression.length());
        int before = (this.rule(jiequ).replace(" ","")).length();
        int end = (this.rule(after).replace(" ","")).length();
        StringBuffer dw=new StringBuffer();
        for (String data:datas
        ) {
            if(columns.contains(data)){
                List<String> maps1 = workMapper.unUseNo(tableName, data);
                for (String cd:maps1
                ) {
                    String trim = cd.replace(" ","");
                    Integer strm2 = Integer.parseInt(trim.substring(before,trim.length()-end));
                    dw.append(strm2+",");
                }
            }
        }
        StringBuffer str=new StringBuffer();
        for (int i = 1; i <sysRuleModel.getCounter(); i++) {
            str.append(i+",");
        }
        //算法将两个串中的重复数据删掉
        String[] arr1 = str.toString().split(",");
        String[] arr2 = dw.toString().split(",");
        for (int i = 0; i < arr2.length; i++) {
            for (int j = 0; j < arr1.length; j++) {
                if (arr1[j].equals(arr2[i])) {
                    arr1[j] = "";
                }
            }
        }
        for (int j = 0; j < arr1.length; j++) {
            if (!"".equals(arr1[j])) {
                sb.append(arr1[j] + ",");
            }
        }
        Map<String, String> mapss = new HashMap<>();//将需要传前台的数据放进map中
        if (sb.toString().length() > 0) {
            String[] split = sb.toString().substring(0, sb.toString().length() - 1).split(",");
            for (int i = 0; i <split.length; i++) {//拼接成标准格式
                String substring = this.rule(jiequ)+split[i]+this.rule(after);
                mapss.put(Integer.toString(i), substring);
            }
        }
        json.setObject(mapss);
        json.setFlag(0);
        return json;
    }
    public ToJson UseNo(HttpServletRequest request, Integer flowId) {
        ToJson json = new ToJson<>();
        List<List<Map<String, String>>> maps=new ArrayList<>();
        String tableName = "flow_data_" + flowId;
        List<FlowFormType> allFlowForm = wfeFormTypeMapper.getFrombyFlowId(flowId);
        FlowFormType flowFormType = allFlowForm.get(0);
        //获取表单信息
        Document document = HtmlUtil.getDom(flowFormType.getPrintModel());
        String sqlType = "xoa"+(String) request.getSession().getAttribute(
                "loginDateSouse");

        //获取该表数据库中的所有的列
        Map<String, Object> param = new HashMap<String, Object>();
        param.put("tableName", tableName);
        param.put("tableSchema", sqlType);
        String[] datas = request.getParameter("datas").split(",");
        List<String> columns = workMapper.showColumns(param);
        for (String data:datas
        ) {
            if(columns.contains(data)){
                maps.add(workMapper.UseNo(tableName,data));
            }
        }
        //获取该表所有的列
        /*List<String> columns = workMapper.showColumns(param);
        for (String column:columns
        ) {
            if(column.contains("DATA_")){
                String documentDataType = HtmlUtil.getDocumentDataType(document, column);
                if(documentDataType!=null&&documentDataType!=""){
                    if(documentDataType.equals("autocode")){
                        maps.add(workMapper.UseNo(tableName,column));
                    }
                }
            }
        }*/
        json.setObject(maps);
        json.setFlag(0);
        return json;
    }

    public ToJson checkRunId(HttpServletRequest request,Integer flowId, Integer runId){
        ToJson json = new ToJson<>();
        String dataNum = request.getParameter("dataNum");
        String tableName = "flow_data_" + flowId;
        String sqlType = "xoa"+(String) request.getSession().getAttribute(
                "loginDateSouse");
        //获取该表数据库中的所有的列
        Map<String, Object> param = new HashMap<String, Object>();
        param.put("tableName", tableName);
        param.put("tableSchema", sqlType);
        List<String> columns = workMapper.showColumns(param);
        if(columns.size()>0){
            if(columns.contains(dataNum)){
                String s = workMapper.selectDatas(runId, tableName,dataNum);
                if(s!=null&&s!=""){
                    json.setObject(1);
                }else{
                    json.setObject(0);
                }
            }else {
                json.setObject(0);
            }
        }else{
            json.setObject(0);
        }
        json.setFlag(0);
        return json;
    }
    //查询出count+1的数据
    public SysRuleModel getRuleByIds(SysRuleModel sysRule,
                                     HttpServletRequest request,Integer count) {
        SysRuleModel sys = sysRuleModelMapper.getRuleById(sysRule);
        String expression = sys.getExpression();
        String transforedExpression = this.transfor(expression, request, sys);
        List<String> titleList = new ArrayList<String>();
        List<String> expressionList = new ArrayList<String>();
        sys.setExpressionStr(expression);
        String expressionStr = sys.getExpressionStr();
        // 定义正则表达式
        Pattern pattern = Pattern.compile("(?<=\\[)(.+?)(?=\\])");
        Matcher matcher = pattern.matcher(expression);
        Calendar now = Calendar.getInstance();
        // 匹配规则字段
        String str = null;

        while (matcher.find()) {
            switch (matcher.group()) {
                // 短年份
                case SHOT_YEAR:
                    str = String.valueOf(now.get(Calendar.YEAR));
                    titleList.add("短年份");
                    expressionList.add(str.substring(str.length() - 2));
                    expressionStr = expressionStr.replace("[YY]",
                            " " + str.substring(str.length() - 2) + " ");
                    break;
                // 年份
                case All_YEAR:
                    str = String.valueOf(now.get(Calendar.YEAR));
                    titleList.add("全年份");
                    expressionList.add(str);
                    expressionStr = expressionStr.replace("[ALL_YY]", " " + str
                            + " ");
                    break;
                // 日期
                case DATE:
                    str = (new SimpleDateFormat("yyyy-MM-dd"))
                            .format(new Date());
                    titleList.add("日期");
                    expressionList.add(str);
                    expressionStr = expressionStr.replace("[DATE]", " " + str
                            + " ");
                    break;
                // 日期带时分秒
                case DATE_TIME:
                    str = (new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"))
                            .format(new Date());
                    titleList.add("日期时间");
                    expressionList.add(str);
                    expressionStr = expressionStr.replace("[DATE_TIME]", " "
                            + str + " ");
                    break;
                // 01 02 日
                case H_MOS:
                    int day = now.get(Calendar.DAY_OF_MONTH);
                    if (day < 10) {
                        str = "0" + day;
                    } else {
                        str = String.valueOf(day);
                    }
                    titleList.add("长日期");
                    expressionList.add(str);
                    expressionStr = expressionStr.replace("[H_MOS]", " " + str
                            + " ");
                    break;
                // 1 2 日
                case H_MO:
                    str = String.valueOf(now.get(Calendar.DAY_OF_MONTH));
                    titleList.add("短日期");
                    expressionList.add(str);
                    expressionStr = expressionStr.replace("[H_MO]", " " + str
                            + " ");
                    break;
                // 01 02 月份
                case MONTHS:
                    int month = now.get(Calendar.MONTH) + 1;
                    if (month < 10) {
                        str = "0" + month;
                    } else {
                        str = String.valueOf(month);
                    }
                    titleList.add("长月份");
                    expressionList.add(str);
                    expressionStr = expressionStr.replace("[MONTHS]", " " + str
                            + " ");
                    break;
                // 1 2 月份
                case MONTH:
                    str = String.valueOf(now.get(Calendar.MONTH) + 1);
                    titleList.add("短月份");
                    expressionList.add(str);
                    expressionStr = expressionStr.replace("[MONTH]", " " + str
                            + " ");
                    break;
                // 获取计数器
                case COUNTER:
                    int number = sys.getCounter();
                    String str1 = String.format("%0" + sys.getDigit() + "d", number+count);
                    str = String.valueOf(sys.getCounter());
                    expressionStr = expressionStr.replace("[COUNTER]", " "
                            + str1 + " ");
                    break;

            }
        }
        // 获取计数器
        str = String.valueOf(sys.getCounter());
        SysRuleModel ruleById = new SysRuleModel();
        ruleById.setId(sysRule.getId());
        ruleById.setCounter((Integer.parseInt(str))+count);
        //生成新的自动编号后将flow_data_id中的自动编号字段更改掉
        String dataNum = request.getParameter("dataNum");
        String runId = request.getParameter("runId");
        String flowId = request.getParameter("flowId");
        //获取flow_run数据
        FlowRun flowRun = wfeFlowRunMapper.selectBuRunId(Integer.parseInt(runId));
        Map<String, Object> maps = new HashMap<String, Object>();
        String sqlType = "xoa" + (String) request.getSession().getAttribute(
                "loginDateSouse");
        String tableName = "flow_data_" + flowId;
        maps.put("tableName", tableName);
        maps.put("runId", runId);
        maps.put("tableSchema", sqlType);
        //获取数据并检索是否有表，没有表则新建
        Map<String, Object> map = aiController.getFlowData("flow_data_"+flowId, sqlType, Integer.parseInt(runId), Integer.parseInt(flowId));
        //用于存储数据库插入的字段
        List<String> key = new ArrayList<String>();
        List<Object> value = new ArrayList<Object>();
        //获取该表所有的列
        List<String> columns = workMapper.showColumns(maps);
        if (map == null || map.size() == 0) {//map为空则向表中插入一条数据
            key.add("RUN_ID");
            value.add(String.valueOf(runId));
            key.add("RUN_NAME");
            value.add(flowRun.getRunName());
            key.add("BEGIN_TIME");
            value.add(DateFormat.getStrDate(new Date()));
            key.add("BEGIN_USER");
            value.add(flowRun.getBeginUser());
            for (String s : columns) {
                if (s.contains("DATA_")) {
                    if(s.equals(dataNum)){
                        key.add(s);
                        value.add(expressionStr);
                    }else {
                        key.add(s);
                        value.add("");
                    }
                }
            }
            maps.put("tableName", tableName);
            maps.put("keys", key);
            maps.put("values", value);
            workMapper.insert(maps);
        }else{//有数据则更改自动编号对应字段
            if(!columns.contains(dataNum)){//数据库表中是否含有此字段，没有的则添加
                Map<String, Object> param = new HashMap();
                List<String> insertData = new ArrayList<String>();
                insertData.add(dataNum);
                param.put("tableName", tableName);
                param.put("keys", insertData);
                workMapper.addcolumn(param);
            }
            Map<String,Object> updateMap=new HashMap<>();
            updateMap.put("runId",runId);
            updateMap.put("tableName","flow_data_" + flowId);
            List<String> updateKey = new ArrayList<String>();
            updateKey.add(dataNum + "=" + "'" +expressionStr  + "'");
            updateMap.put("keys", updateKey);
            workMapper.update(updateMap);
        }
        this.updateRuleById(ruleById);//将计数器位数改为最大的
        titleList.add("计数器");
        expressionList.add(str);
        sys.setExpressionStr(expressionStr);
        sys.setRuleTitles(titleList);
        sys.setRuleExps(expressionList);
        return sys;
    }
    @Override
    public ToJson selectCount(HttpServletRequest request) {
        ToJson json = new ToJson<DocumentModel>();
        Cookie redisSessionCookie = CookiesUtil.getCookieByName(request, "redisSessionId");
        Users user = SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users(), redisSessionCookie);
        Map<String, Object> param = new HashMap<String, Object>();
        Map<String, Object> show = new HashMap<String, Object>();
        param.put("userId", user.getUserId());
        int count=0;
        List<DocumentModelFlowRunPrcs> datas = documentModelMapper.selWillDocSendOrReceiveNotOrderBy(param);
        // 时限
        for (DocumentModelFlowRunPrcs d : datas) {
            Users users1 = usersMapper.SimplefindUsersByuserId(d.getCreater());
            if (users1 != null) {
                d.setCreaterName(users1.getUserName());
            }
            SysCode gwtype = sysCodeMapper.getSingleCode("GWTYPE", d.getDispatchType());
            if (gwtype != null) {
                d.setCodeName(gwtype.getCodeName());
            }
            //获取发起人
            d.setAvatar(users1.getAvatar() == null ? "" : users1.getAvatar());
            // 超时计算方法  0-本步骤接收后开始计时,1-上一步骤转交后开始计时
            if ("0".equals(d.getTimeOutType())) {
                // 判断该步骤状态  1-未接收,2-办理中,3-转交下一步，下一步经办人无人接收,4-已办结,5-自由流程预设步骤,6-已挂起
                if (d.getPrFlag().equals(2)) {
                    if (!StringUtils.checkNull(d.getPrcsTime())) {
                        setTimeOutStr(d, DateFormat.getTime(d.getPrcsTime()));
                    }
                } else if (d.getPrFlag().equals(1)) {
                    if (!StringUtils.checkNull(d.getTimeOut())) {
                        d.setIfOutTime(true);
                        d.setTimeOutStr("计时未开始");
                    }
                }
            } else if ("1".equals(d.getTimeOutType())) {
                if (!d.getRealPrcsId().equals(1)) {
                    if (!d.getPrFlag().equals(3) && !d.getPrFlag().equals(4)) {
                        if (!StringUtils.checkNull(d.getCreateTime())) {
                            setTimeOutStr(d, DateFormat.getTime(d.getCreateTime()));
                        }
                    } else if (d.getPrFlag().equals(3)) {
                        d.setTimeOutStr("计时已结束");
                        d.setIfOutTime(true);
                    } else if (d.getPrFlag().equals(4)) {
                        d.setTimeOutStr("计时已结束");
                        d.setIfOutTime(true);
                    }
                }
            }
            if(!StringUtils.checkNull(d.getTimeOutStr())){
                if((d.getTimeOutStr()).contains("超时")){
                    count++;
                }
            }
        }
        show.put("timeOutDocument",count);
        show.put("readDocument",toBeReadMapper.selectCount(user.getUserId()));
        param.put("documentType", "0");
        show.put("receiveDocument",documentModelMapper.selMyDocSendOrReceiveCounts(param));
        param.remove("documentType");
        param.put("documentType", "1");
        show.put("sendDocument",documentModelMapper.selMyDocSendOrReceiveCounts(param));
        json.setObject(show);
        json.setFlag(0);
        json.setMsg("ok");
        return json;
    }
    @Override
    public ToJson selectWillCount(HttpServletRequest request) {
        ToJson json = new ToJson<DocumentModel>();
        Cookie redisSessionCookie = CookiesUtil.getCookieByName(request, "redisSessionId");
        Users user = SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users(), redisSessionCookie);
        Map<String, Object> param = new HashMap<String, Object>();
        Map<String, Object> show = new HashMap<String, Object>();
        param.put("userId", user.getUserId());
        param.put("documentType", "0");
        param.put("prcsFlag", 1);
        Integer waitSend = documentModelMapper.selWillDocSendOrReceiveCounts(param);//待办发文
        show.put("waitSend",waitSend);

        param.remove("documentType");
        param.remove("prcsFlag");
        param.put("documentType", "0");
        param.put("prcsFlag", 2);
        Integer overSend = documentModelMapper.selWillDocSendOrReceiveCounts(param);//已办发文
        show.put("overSend",overSend);

        param.remove("documentType");
        param.remove("prcsFlag");
        param.put("documentType", "1");
        param.put("prcsFlag", 1);
        Integer waitReceive = documentModelMapper.selWillDocSendOrReceiveCounts(param);//待办收文
        show.put("waitReceive",waitReceive);

        param.remove("documentType");
        param.remove("prcsFlag");
        param.put("documentType", "1");
        param.put("prcsFlag", 2);
        Integer overReceive = documentModelMapper.selWillDocSendOrReceiveCounts(param);//已办收文
        show.put("overReceive",overReceive);
        json.setObject(show);
        json.setFlag(0);
        json.setMsg("ok");
        return json;
    }
    @Override
    public ToJson selectBytypeCount(HttpServletRequest request){
        ToJson json =new ToJson();
        List<SysCode> gwtype = sysCodeMapper.getSysCode("GWTYPE");
        Cookie redisSessionCookie = CookiesUtil.getCookieByName(request, "redisSessionId");
        Users user = SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users(), redisSessionCookie);
        Map<String, Object> param = new HashMap<String, Object>();
        Map<String, Object> show = new HashMap<String, Object>();
        param.put("userId", user.getUserId());
        for (SysCode sys:gwtype
        ) {
            param.put("dispatchType", sys.getCodeNo());
            Integer overReceive = documentModelMapper.selWillDocSendOrReceiveCounts(param);
            show.put(sys.getCodeName(),overReceive);
            param.remove("dispatchType");
        }
        json.setFlag(0);
        json.setObject(show);
        return json;
    }


    //获取自定义规则样式
    @Override
    public String rule(String expressionStr) {
        List<String> titleList = new ArrayList<String>();
        List<String> expressionList = new ArrayList<String>();
        // 定义正则表达式
        Pattern pattern = Pattern.compile("(?<=\\[)(.+?)(?=\\])");
        Matcher matcher = pattern.matcher(expressionStr);
        Calendar now = Calendar.getInstance();
        // 匹配规则字段
        String str = null;

        while (matcher.find()) {
            switch (matcher.group()) {
                // 短年份
                case SHOT_YEAR:
                    str = String.valueOf(now.get(Calendar.YEAR));
                    titleList.add("短年份");
                    expressionList.add(str.substring(str.length() - 2));
                    expressionStr = expressionStr.replace("[YY]",
                            " " + str.substring(str.length() - 2) + " ");
                    break;
                // 年份
                case All_YEAR:
                    str = String.valueOf(now.get(Calendar.YEAR));
                    titleList.add("全年份");
                    expressionList.add(str);
                    expressionStr = expressionStr.replace("[ALL_YY]", " " + str
                            + " ");
                    break;
                // 日期
                case DATE:
                    str = (new SimpleDateFormat("yyyy-MM-dd"))
                            .format(new Date());
                    titleList.add("日期");
                    expressionList.add(str);
                    expressionStr = expressionStr.replace("[DATE]", " " + str
                            + " ");
                    break;
                // 日期带时分秒
                case DATE_TIME:
                    str = (new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"))
                            .format(new Date());
                    titleList.add("日期时间");
                    expressionList.add(str);
                    expressionStr = expressionStr.replace("[DATE_TIME]", " "
                            + str + " ");
                    break;
                // 01 02 日
                case H_MOS:
                    int day = now.get(Calendar.DAY_OF_MONTH);
                    if (day < 10) {
                        str = "0" + day;
                    } else {
                        str = String.valueOf(day);
                    }
                    titleList.add("长日期");
                    expressionList.add(str);
                    expressionStr = expressionStr.replace("[H_MOS]", " " + str
                            + " ");
                    break;
                // 1 2 日
                case H_MO:
                    str = String.valueOf(now.get(Calendar.DAY_OF_MONTH));
                    titleList.add("短日期");
                    expressionList.add(str);
                    expressionStr = expressionStr.replace("[H_MO]", " " + str
                            + " ");
                    break;
                // 01 02 月份
                case MONTHS:
                    int month = now.get(Calendar.MONTH) + 1;
                    if (month < 10) {
                        str = "0" + month;
                    } else {
                        str = String.valueOf(month);
                    }
                    titleList.add("长月份");
                    expressionList.add(str);
                    expressionStr = expressionStr.replace("[MONTHS]", " " + str
                            + " ");
                    break;
                // 1 2 月份
                case MONTH:
                    str = String.valueOf(now.get(Calendar.MONTH) + 1);
                    titleList.add("短月份");
                    expressionList.add(str);
                    expressionStr = expressionStr.replace("[MONTH]", " " + str
                            + " ");
                    break;

            }
        }
        return expressionStr;
    }
    //直接上传pdf后将其他三个正文字段数据清除
    @Override
    public ToJson setMainFile(Integer id){
        ToJson json=new ToJson();
        int i = documentModelMapper.setMainFile(id);
        if(i>0){
            json.setMsg("ok");
            json.setFlag(0);
        }
        return  json;
    }
    //直接上传word文件后将pdf和修订文件对应的字段清除
    @Override
    public ToJson clearMainpdf(Integer id){
        ToJson json=new ToJson();
        int i = documentModelMapper.clearMainpdf(id);
        if(i>0){
            json.setMsg("ok");
            json.setFlag(0);
        }
        return  json;
    }

    //电建门户公文管理待办数据获取
    public BaseWrappers getAssignDocData(HttpServletRequest request, String documentType, String dispatchType, String printDate, String title, Integer docStatus, Integer page, Integer pageSize, Integer prcsFlag) {
        BaseWrappers wrappers = new BaseWrappers();
        wrappers.setStatus(true);
        wrappers.setFlag(false);
        List<DocumentModelFlowRunPrcs> assignData = new ArrayList<DocumentModelFlowRunPrcs>();
        List<DocumentModelFlowRunPrcs> commonData = new ArrayList<DocumentModelFlowRunPrcs>();
        String flowId = request.getParameter("flowId");
        Cookie redisSessionId = CookiesUtil.getCookieByName(request, "redisSessionId");
        Users users = SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users(), redisSessionId);
        if (StringUtils.checkNull(users.getUserId())) {
            wrappers.setMsg("用户信息过期");
            return wrappers;
        }
        if (StringUtils.checkNull(dispatchType)) {
            dispatchType = null;
        }
        if (StringUtils.checkNull(printDate)) {
            printDate = null;
        }
        if (StringUtils.checkNull(title)) {
            title = null;
        }

        page = (page - 1) * pageSize;
        Map<String, Object> param = new HashMap<String, Object>();
        param.put("userId", users.getUserId());
        param.put("documentType", documentType);
        param.put("printDate", printDate);
        param.put("dispatchType", dispatchType);
        param.put("page", page);
        param.put("pageSize", pageSize);
        param.put("prcsFlag", prcsFlag);
        param.put("title", title);
        param.put("docStatus", docStatus);
        param.put("flowId", flowId);
        List<DocumentModelFlowRunPrcs> datas = documentModelMapper.selWillDocSendOrReceive(param);
        // 时限
        for (DocumentModelFlowRunPrcs d : datas) {
            Users users1 = usersMapper.SimplefindUsersByuserId(d.getCreater());
            if (users1 != null) {
                d.setCreaterName(users1.getUserName());
            }
            SysCode gwtype = sysCodeMapper.getSingleCode("GWTYPE", d.getDispatchType());
            if (gwtype != null) {
                d.setCodeName(gwtype.getCodeName());
            }
            //获取发起人
            d.setAvatar(users1.getAvatar() == null ? "" : users1.getAvatar());

            // 超时计算方法  0-本步骤接收后开始计时,1-上一步骤转交后开始计时
            if ("0".equals(d.getTimeOutType())) {
                // 判断该步骤状态  1-未接收,2-办理中,3-转交下一步，下一步经办人无人接收,4-已办结,5-自由流程预设步骤,6-已挂起
                if (d.getPrFlag().equals(2)) {
                    if (!StringUtils.checkNull(d.getPrcsTime())) {
                        setTimeOutStr(d, DateFormat.getTime(d.getPrcsTime()));
                    }
                } else if (d.getPrFlag().equals(1)) {
                    if (!StringUtils.checkNull(d.getTimeOut())) {
                        d.setIfOutTime(true);
                        d.setTimeOutStr("计时未开始");
                    }
                }
            } else if ("1".equals(d.getTimeOutType())) {
                if (!d.getRealPrcsId().equals(1)) {
                    if (!d.getPrFlag().equals(3) && !d.getPrFlag().equals(4)) {
                        if (!StringUtils.checkNull(d.getCreateTime())) {
                            setTimeOutStr(d, DateFormat.getTime(d.getCreateTime()));
                        }
                    } else if (d.getPrFlag().equals(3)) {
                        d.setTimeOutStr("计时已结束");
                        d.setIfOutTime(true);
                    } else if (d.getPrFlag().equals(4)) {
                        d.setTimeOutStr("计时已结束");
                        d.setIfOutTime(true);
                    }
                }
            }
            if (d.getPrintDate().length() > 10) {
                d.setPrintDate(d.getPrintDate().substring(0, 10));
            }
            if (d.getPrcsTime() != null && !"".equals(d.getPrcsTime())) {
                String s = d.getPrcsTime();
                d.setPrcsTime(s.substring(0, s.length() - 2));
            }

            //-----------------------------判断开始---------------------------------------------------
            FlowRunPrcs flowRunPrcs = flowRunPrcsMapper.selectByPrimaryKey(d.getFrpId());
            Map<String, Object> map = new HashMap();
            map.put("runId", flowRunPrcs.getRunId());
            map.put("prcsId", flowRunPrcs.getPrcsId());
            map.put("flowPrcs", flowRunPrcs.getFlowPrcs());
            map.put("userId", users.getUserId());
            Boolean isAssignData = false;
            //获取所有增加经办人数据
            List<FlowRunPrcs> frps = wfeFlowRunPrcsMapper.getAssignData(map);
            StringBuffer onWork = new StringBuffer();
            StringBuffer endWork = new StringBuffer();
            StringBuffer fawonWork = new StringBuffer();
            StringBuffer fawendWork = new StringBuffer();
            Boolean isFawData = false;
            if (frps.size() > 0) {//含有增加经办人
                for (FlowRunPrcs frp : frps) {
                    if (frp.getOpaddUser().equals(flowRunPrcs.getUserId())&&frp.getFlowPrcs().equals(flowRunPrcs.getFlowPrcs())) {
                        if(Integer.parseInt(frp.getPrcsFlag()) < 3){
                            onWork.append(frp.getUserId() + ",");
                            isAssignData = true;
                        }else{
                            endWork.append(frp.getUserId() + ",");
                        }
                    }
                    if(!StringUtils.checkNull(frp.getComment())&&frp.getComment().equals("1")){
                        d.setComment(String.valueOf(frp.getId()));
                    }
                }
                List<FlowAssignWithBLOBs> assign = flowAssignMapper.getAssigns(flowRunPrcs.getRunId(), flowRunPrcs.getPrcsId(), String.valueOf(flowRunPrcs.getFlowPrcs()));
                if (assign.size() > 0) {
                    for (FlowAssignWithBLOBs faw : assign) {
                        if (faw.getAssignUser().equals(flowRunPrcs.getUserId())&&faw.getFlowPrcs().equals(flowRunPrcs.getFlowPrcs())) {
                            if(faw.getHandleStatus() != 2){
                                fawonWork.append(faw.getHandleUser() + ",");
                                isFawData = true;
                            }else{
                                fawendWork.append(faw.getHandleUser() + ",");
                            }
                        }
                        //获取交办表中的数据对应的frp中的数据
                        Map<String,Object> assMap=new HashMap<>();
                        assMap.put("userId",faw.getHandleUser());
                        assMap.put("flowPrcs",faw.getFlowPrcs());
                        assMap.put("prcsId",faw.getPrcsId());
                        assMap.put("runId",faw.getRunId());
                        List<FlowRunPrcs> fawFrp = wfeFlowRunPrcsMapper.selectFind(assMap);
                        if(fawFrp.size()>0){
                            if(!StringUtils.checkNull(fawFrp.get(0).getComment())&&fawFrp.get(0).getComment().equals("1")){
                                d.setComment(String.valueOf(fawFrp.get(0).getId()));
                            }
                        }
                    }
                }
                if (isAssignData||isFawData) {//需显示在经办的数据
                    //正在办理中的增加经办人的数据
                    String onWorkUsername = null;
                    if (!StringUtils.checkNull(onWork.toString())) {
                        onWorkUsername = usersService.getUserNameById(onWork.toString());
                    }
                    //已经办结的增加经办人数据
                    String endWorkUsername = null;
                    if (!StringUtils.checkNull(endWork.toString())) {
                        endWorkUsername = usersService.getUserNameById(endWork.toString());
                    }
                    Map<String, Object> shouAssign = new HashMap<>();
                    if (onWorkUsername != null) {
                        shouAssign.put("ason", "待办经办人：" + onWorkUsername);
                    }
                    if (endWorkUsername != null) {
                        shouAssign.put("asend", "已办经办人：" + endWorkUsername);
                    }
                    if (assign.size() > 0) {
                        if (isFawData) {
                            //正在办理中的交办数据
                            String fawonWorkUsername = null;
                            if (!StringUtils.checkNull(fawonWork.toString())) {
                                fawonWorkUsername = usersService.getUserNameById(fawonWork.toString());
                            }
                            //已经办结的交办数据
                            String fawendWorkUsername = null;
                            if (!StringUtils.checkNull(fawendWork.toString())) {
                                fawendWorkUsername = usersService.getUserNameById(fawendWork.toString());
                            }
                            if (fawonWorkUsername != null) {
                                shouAssign.put("faon", "待办交办人：" + fawonWorkUsername);
                            }
                            if (fawendWorkUsername != null) {
                                shouAssign.put("faend", "已办交办人：" + fawendWorkUsername);
                            }
                        }
                        d.setHandles(shouAssign);
                        assignData.add(d);
                    } else {
                        //存放至对象中，返回前台
                        d.setHandles(shouAssign);
                        assignData.add(d);
                    }
                    continue;
                } else {//增加经办人全部已办结，放置待办中
                    commonData.add(d);
                }
            } else {//是否含有交办人
                List<FlowAssignWithBLOBs> assign = flowAssignMapper.getAssigns(flowRunPrcs.getRunId(), flowRunPrcs.getPrcsId(), String.valueOf(flowRunPrcs.getFlowPrcs()));
                if (assign.size() > 0) {//有交办人
                    for (FlowAssignWithBLOBs faw : assign) {
                        if (faw.getAssignUser().equals(flowRunPrcs.getUserId())&&faw.getFlowPrcs().equals(flowRunPrcs.getFlowPrcs())) {
                            if(faw.getHandleStatus() != 2){
                                fawonWork.append(faw.getHandleUser() + ",");
                                isFawData = true;
                            }else{
                                fawendWork.append(faw.getHandleUser() + ",");
                            }
                        }
                        //获取交办表中的数据对应的frp中的数据
                        Map<String,Object> assMap=new HashMap<>();
                        assMap.put("userId",faw.getHandleUser());
                        assMap.put("flowPrcs",faw.getFlowPrcs());
                        assMap.put("prcsId",faw.getPrcsId());
                        assMap.put("runId",faw.getRunId());
                        List<FlowRunPrcs> fawFrp = wfeFlowRunPrcsMapper.selectFind(assMap);
                        if(fawFrp.size()>0){
                            if(!StringUtils.checkNull(fawFrp.get(0).getComment())&&fawFrp.get(0).getComment().equals("1")){
                                d.setComment(String.valueOf(fawFrp.get(0).getId()));
                            }
                        }
                    }
                    if (isFawData) {
                        //正在办理中的交办数据
                        String fawonWorkUsername = null;
                        if (!StringUtils.checkNull(fawonWork.toString())) {
                            fawonWorkUsername = usersService.getUserNameById(fawonWork.toString());
                        }
                        //已经办结的交办数据
                        String fawendWorkUsername = null;
                        if (!StringUtils.checkNull(fawendWork.toString())) {
                            fawendWorkUsername = usersService.getUserNameById(fawendWork.toString());
                        }
                        Map<String, Object> shouFaw = new HashMap<>();
                        if (fawonWorkUsername != null) {
                            shouFaw.put("faon", "待办交办人：" + fawonWorkUsername);
                        }
                        if (fawendWorkUsername != null) {
                            shouFaw.put("faend", "已办交办人：" + fawendWorkUsername);
                        }
                        d.setHandles(shouFaw);
                        assignData.add(d);
                        continue;
                    } else {//交办全部已办结，放置待办中
                        commonData.add(d);
                    }
                } else {//无交办和增加经办人数据，属于正常转交
                    commonData.add(d);
                }
            }
        }
        List<DocumentModelFlowRunPrcs> data = documentModelMapper.selWillDocSendOrReceiveCount(param);
        wrappers.setTotal(data.size());
        wrappers.setFlag(true);
        Map<String, Object> showMap = new HashMap();
        showMap.put("commonData", commonData);
        showMap.put("assignData", assignData);
        wrappers.setObject(showMap);
        return wrappers;
    }

    @Override
    public ToJson SupervisionStatistics(HttpServletRequest request, Integer page, Integer pageSize, Integer flowId, String flag) throws ParseException {
        ToJson json = new ToJson();
        //序号    流水号 runId  督办编号 122 标题 43  督办事项 44 督办来源 45 文件文号 47 文件名称 51 截止时间 64 承办部门 70 协办部门 65
        // 当前办理人   办理进度   剩余天数
        String sql = "b.END_TIME,a.run_id,b.work_level,Data_122,Data_43,Data_44,Data_45,Data_47,Data_51,Data_64,Data_70,Data_65,Data_122";
        String tableName = "flow_data_"+flowId;
        Map map = new HashMap();
        map.put("sql",sql);
        map.put("tableName",tableName);
        map.put("flag",flag);
        String title = request.getParameter("title") == null || request.getParameter("title") == "" ?"''":"'"+request.getParameter("title")+"'";
        String fileName = request.getParameter("fileName") == null || request.getParameter("fileName") == "" ?"''":"'"+request.getParameter("fileName")+"'";
        String deptName = request.getParameter("deptName") == null || request.getParameter("deptName") == "" ?"''":"'"+request.getParameter("deptName")+"'";
        String where = "a.Data_43 like concat('%',"+title+",'%') and a.Data_51 like concat('%',"+fileName+",'%') and a.Data_70 like concat('%',"+deptName+",'%')";
        map.put("where",where);
        map.put("page",(page - 1) * pageSize);
        map.put("pageSize",pageSize);
        List<Map<String, Object>> maps = documentModelMapper.SupervisionStatistics(map);
        for (Map map1:maps){
            if (flag.equals("1")){
                String runId = String.valueOf(map1.get("run_id"));
                StringBuffer sb = new StringBuffer();
                if (null != runId){
                    List<FlowRunPrcs> flowRunPrcs1 = flowRunPrcsMapper.selectByRunIdAndPrcsFlag(runId, "1");
                    for (FlowRunPrcs flowRunPrcs:flowRunPrcs1) {
                        sb.append(usersMapper.getUsernameByUserId(flowRunPrcs.getUserId())+",");
                    }
                    List<FlowRunPrcs> flowRunPrcs2 = flowRunPrcsMapper.selectByRunIdAndPrcsFlag(runId, "2");
                    for (FlowRunPrcs flowRunPrcs:flowRunPrcs2) {
                        sb.append(usersMapper.getUsernameByUserId(flowRunPrcs.getUserId())+",");
                    }
                    map1.put("userName",sb.toString());
                }

                SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
                long oneDay = 1000*60*60*24;
                String date_64 = map1.get("Data_64").toString();
                if (null != date_64){
                    Date parse = sdf.parse(date_64);
                    long l = (parse .getTime()- new Date().getTime()) / oneDay;
                    map1.put("day",l);
                }
            }
            map1.put("flowId",flowId);
        }
        json.setFlag(0);
        json.setObj(maps);
        json.setTotleNum(documentModelMapper.SupervisionStatisticsCount(map));
        return json;
    }
    //  每天早上9时执行 督办流程将到期提醒，固定的流程，只针对电建执行
    @Override
    public void sendSms() {
        String sql = "b.RUN_NAME,a.run_id,Data_64";
        String tableName = "flow_data_362";
        Map map = new HashMap();
        map.put("sql", sql);
        map.put("tableName", tableName);
        map.put("flag", 1);
        try {
            List<Map<String, Object>> maps = documentModelMapper.SupervisionStatistics(map);
            for (Map map1 : maps) {
                String runId = String.valueOf(map1.get("run_id"));
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                long oneDay = 1000 * 60 * 60 * 24;
                String date_64 = map1.get("Data_64").toString();
                String runName = map1.get("RUN_NAME").toString();
                if (!StringUtils.checkNull(date_64)) {
                    Date parse = sdf.parse(date_64);
                    int day = (int) ((parse.getTime() - new Date().getTime()) / oneDay);
                    if (day == 3) {
                        List<FlowRunPrcs> flowRunPrcs = flowRunPrcsMapper.selectByRunIdAndPrcsFlag(runId, "2");
                        for (FlowRunPrcs frp : flowRunPrcs
                        ) {
                            addSmsRemind(frp, "admin", frp.getUserId(), "0", "1", "xoa1001");
                        }
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    //发送事务提醒
    public void addSmsRemind(FlowRunPrcs frp, String fromId, String toUserIds, final String tuisong, final String remind, final String sqlType) {
        if (StringUtils.checkNull(remind) || "0".equals(remind)) {
            return;
        }
        if (StringUtils.checkNull(toUserIds)) {
            return;
        }
        //选择人员
        threadPoolTaskExecutor.execute(new Runnable() {
            @Override
            public void run() {
                ContextHolder.setConsumerType("xoa" + sqlType);
                SmsBody smsBody = new SmsBody();
                smsBody.setFromId(fromId);
                smsBody.setSmsType("7");
                smsBody.setSendTime((int) (System.currentTimeMillis() / 1000));
                String context = "您有即将到期的督办任务：" + frp.getFlowRun().getRunName();
                smsBody.setContent(context);
                String smsUrl = "/workflow/work/workform?opflag="+frp.getOpFlag()+"&flowId=" + Integer.valueOf(frp.getFlowRun().getFlowId()) + "&flowStep=" + frp.getPrcsId() + "&runId=" + frp.getRunId() + "&prcsId=" + frp.getFlowPrcs();
                smsBody.setRemindUrl(smsUrl);
                smsService.saveSms(smsBody, toUserIds.toString(), remind, tuisong, "督办流程即将到期提醒", context, sqlType);
            }
        });

    }


    public Integer updateDocumentTitle(String title,  Integer runId){
        return documentModelMapper.updateDocumentTitle(title,runId);
    }


    private void copyFiles(String module, String company, List<Attachment> newAttachmentList, List<Attachment> flowAttachmentList, String oldModule) throws IOException {
        // 循环遍历拷贝
        for (int i = 0, size = flowAttachmentList.size(); i < size; i++) {

            Attachment flowAttachment = flowAttachmentList.get(i);

            // 文件存储头
            StringBuilder uploadHead = FileUploadUtil.getUploadHead();

            // 当前年月
            String ym = new SimpleDateFormat("yyMM").format(new Date());

            // 时间戳数字串
            String attachID = String.valueOf(Math.abs((int) System.currentTimeMillis()));

            // 文件存储路径
            StringBuilder flowFilePath = uploadHead.append(System.getProperty("file.separator")).
                    append(company).append(System.getProperty("file.separator")).
                    append(oldModule).append(System.getProperty("file.separator")).
                    append(flowAttachment.getYm()).append(System.getProperty("file.separator"));

            StringBuilder uploadHead2 = FileUploadUtil.getUploadHead();

            StringBuilder notifyFilePath = uploadHead2.append(System.getProperty("file.separator")).
                    append(company).append(System.getProperty("file.separator")).
                    append(module.trim()).append(System.getProperty("file.separator")).
                    append(ym).append(System.getProperty("file.separator"));


            //获得模块id
            byte mid = 0;
            for (ModuleEnum em : ModuleEnum.values()) {
                if (em.getName().equals(module.trim())) {
                    mid = (byte) em.getIndex();
                }
            }

            File flowFile = new File(flowFilePath.append(flowAttachment.getAttachId()).append(".").append(flowAttachment.getAttachName()).toString());

            if (!flowFile.exists()) {
                continue;
            }

            File notifyFile = new File(notifyFilePath.append(attachID).append(".").append(flowAttachment.getAttachName()).toString());

            FileUploadUtil.copyFileUsingFileChannels(flowFile, notifyFile);


            // 保存进数据库
            Attachment attachment = new Attachment();
            attachment.setAttachId(attachID);
            attachment.setModule(mid);
            attachment.setAttachFile(flowAttachment.getAttachFile());
            attachment.setAttachName(flowAttachment.getAttachName());
            attachment.setYm(ym);
            attachment.setAttachSign(new Long(0));
            attachment.setDelFlag((byte) 0);
            attachment.setPosition((byte) 2);
            attachment.setIsImage((byte) 0);
            attachment.setSize(Convert.convertFileSize(flowFile.length()));
            attachment.setTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));

            // 把附件信息存储进数据库中
            attachmentMapper.insertSelective(attachment);

            String attUrl = "AID=" + attachment.getAid() + "&MODULE="+ module + "&COMPANY=" + company + "&YM=" + attachment.getYm() + "&ATTACHMENT_ID=" + attachment.getAttachId() +
                    "&ATTACHMENT_NAME=" + attachment.getAttachName() + "&FILESIZE=" + attachment.getFileSize();

            attachment.setAttUrl(attUrl);

            newAttachmentList.add(attachment);
        }
    }
}
